2012-10-10 34 views
2

我从网络服务的SOAP信封的回应如下:提取XML在C#

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> 
<s:Body> 
    <ProcessTranResponse xmlns="http://www.polaris.co.uk/XRTEService/2009/03/"> 
    <ProcessTranResult xmlns:a="http://schemas.datacontract.org/2004/07/XRTEService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> 
     <a:PrintFormFileNameContents i:nil="true"/> 
     <a:ResponseXML>response_message</a:ResponseXML> 
    </ProcessTranResult> 
    </ProcessTranResponse> 
</s:Body> 

我想response_message给一个字符串变量。我试着做

XDocument doc = XDocument.Parse(Response); 
XNamespace xmlnsa = "http://schemas.datacontract.org/2004/07/XRTEService"; 
var ResponseXML = doc.Descendants(xmlnsa + "ResponseXML"); 

当我使用的手表我看到我的ResponseXML -> Results View[0] -> Valueresponse_message,但我无法弄清楚什么是下一个步骤,从C#得到价值。

回答

2

XContainer.Descendants返回元素的集合。那么你应该尝试这样的事:

foreach (XElement el in ResponseXML) 
{ 
    Console.WriteLine(el.Value); 
} 

或者你也可以做这样的事情,如果你知道有永远只有一个反应:

XDocument doc = XDocument.Parse(Response); 

XNamespace xmlnsa = "http://schemas.datacontract.org/2004/07/XRTEService"; 

XElement ResponseXML = (from xml in XMLDoc.Descendants(xmlnsa + "ResponseXML") 
         select xml).FirstOrDefault(); 

string ResponseAsString = ResponseXML.Value; 
+0

另外doc.Descendants(xmlnsa +“ResponseXML”)。First()。Value ;使用Linq工作。谢谢! – user1734523

+0

不客气!请注意,如果后代列表为空,则'.First()'可能会抛出异常...... –

+0

如果FirstOrDefault返回null,则''ResponseXML.Value'将引发异常。 –

1

您可以使用多个解决方案来满足你的目的,而你可能想引入xml内容的结构或不。

静态态度

你可以简单地使用:

doc.LastChild.FirstChild.FirstChild.LastChild.InnerText; 

读取XML结构

XmlDocument _doc = new XmlDocument(); 
doc.LoadXml(_stream.ReadToEnd()); 

然后像这样的东西找到所需数据

您可以编写一些额外的代码行来引入命名空间和其他xml内容来查找/映射可用数据,通过看一下extracting-data-from-a-complex-xml-with-linq