有人可以告诉我如何在.NET 3.5 Framework下使用XPath和C#从下面的XML中提取Errors元素吗?
<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<ns1:do_OTA_VehAvailRateRQResponse xmlns:ns1="urn:vanguard-web-webservices-ota-IOTA" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<return xsi:type="xsd:string"><OTA_VehAvailRateRS TimeStamp="2013-04-03T18:16:00" TransactionIdentifier="215997103" SequenceNmbr="1" Target="Production" Version="2.0" xmlns="http://www.opentravel.org/OTA/2003/05">
<Errors>
<Error Type="1" Code="999">COMPANY NAME FIELD IS INVALID</Error>
</Errors>
</OTA_VehAvailRateRS>
</return>
</ns1:do_OTA_VehAvailRateRQResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
答案 0 :(得分:0)
使用强>:
//*[name()='Errors']
这将选择XML文档中的任何元素,其名称为“Errors” - 无论元素的名称空间如何。
或者,如果您想更精确并考虑到元素所在的确切命名空间,您需要使用XmlNamespaceManager
对象并注册前缀和命名空间之间所需的任何关联使用 AddNamespace()
method 。
答案 1 :(得分:0)
试试这段代码:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc .LoadXml(xmlSting); //If u have a xml string, you can create xmlDocument like this, otherwise u can use file name to create xmlDocument.
String error = .SelectSingleNode("SOAP-ENV:Envelope/SOAP-ENV:Body/return/Errors/Error").Value;
答案 2 :(得分:0)
XmlNodeList errorNodes=new XmlDocument().Load("xmlFilePath").GetElementsByTagName("Errors");
答案 3 :(得分:0)
如果您没有向我们展示您的代码,我们无法判断您哪里出错了。
但我们可以猜到。您的Errors元素位于命名空间中,并且未能识别这一事实是缺乏经验的常见错误,我很乐意打赌这是您的错误。
要在命名空间中查找元素,您需要一个路径,例如// e:错误,其中前缀e被绑定(在C#API级别)到命名空间http://www.opentravel.org/OTA/2003/05。
(对不起,你没有说你没经验。我推断这是因为如果你有经验,你会发布你的XPath代码。)