如何使用 Xpath 在 C# 中读取 XML

问题描述:

我有这个 XML

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <GetSKUsPriceAndStockResponse xmlns="http://tempuri.org/">
      <GetSKUsPriceAndStockResult>
        <RequestStatus>
          <DateTime>2/28/2012 5:28:05 PM</DateTime>
          <Message>S200</Message>
        </RequestStatus>
        <SKUsDetails>
          <SKUDetails>
            <SKU>N82E16834230265</SKU>
            <Model>X54C-NS92</Model>
            <Stock>true</Stock>
            <Domain>newegg.com</Domain>
            <SalePrice>439.99</SalePrice>
            <ShippingCharge>0.00</ShippingCharge>
            <Currency>USD</Currency>
          </SKUDetails>
        </SKUsDetails>
      </GetSKUsPriceAndStockResult>
    </GetSKUsPriceAndStockResponse>
  </soap:Body>
</soap:Envelope>

如何使用 XPath 读取 节点?.上面 XML 的 XNamespace 是什么?

How can I read <SKUDetails> Node using XPath?. What will be XNamespace for above XML?

使用 XPath 和 XmlDocument (C#) 操作 XML 数据

最好使用 LINQ toXML,因为您使用的是 .net 4.0,无需学习 XPath 来遍历 xml 树.

its better to use LINQ to XML as your are using .net 4.0 and there is no need to learn XPath to traverse the xml tree.

不确定 xpath 表达式,但您可以像这样编码

Not sure about the xpath expression but you can code like this

string fileName = "data.xml";
XPathDocument doc = new XPathDocument(fileName);
XPathNavigator nav = doc.CreateNavigator();

// Compile a standard XPath expression
XPathExpression expr; 
expr = nav.Compile("/GetSKUsPriceAndStockResponse/GetSKUsPriceAndStockResult/SKUsDetails/SKUDetails");
XPathNodeIterator iterator = nav.Select(expr);
try
{
  while (iterator.MoveNext())
  {

  }
}
catch(Exception ex) 
{
   Console.WriteLine(ex.Message);
}