2016-12-18 92 views
1

我还在使用XML,并且在我正在处理的这个项目上遇到问题。我需要从C#XmlDocument中提取特定的xml元素。在下面的例子中,我想从RATING标签中取出ns:AMOUNT元素(应该是结果193.13)。你会如何正确地做到这一点?非常感谢!从XmlDocument中提取XML元素

<?xml version="1.0" encoding="UTF-8" ?> 
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> 
    <soapenv:Body> 
     <ns:getResp xmlns:ns="http://example"> 
      <ns:jobReturn> 
       <ns:ITEM> 
        <ns:AMOUNT>24.7</ns:AMOUNT> 
       </ns:ITEM> 
       <ns:RATING> 
        <ns:RefNum>1234567890</ns:RefNum> 
        <ns:AMOUNT>193.13</ns:AMOUNT> 
       </ns:RATING> 
      </ns:jobReturn> 
     </ns:getResp> 
    </soapenv:Body> 
</soapenv:Envelope> 

回答

1

我认为你的问题发生,你需要XmlNamespaceManager来处理ns部分。所以

XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.Load(@"your.xml"); 
XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable); 
ns.AddNamespace("ns", "http://example"); 
XmlNode node = xmlDoc.SelectSingleNode("//ns:RATING/ns:AMOUNT", ns); 
var result = node.InnerText;