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

SOF*_*ser 9 c# xml .net-4.0

我有这个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>
Run Code Online (Sandbox Code Playgroud)

如何<SKUDetails>使用XPath 读取Node?以上XML的XNamespace是什么?

Pra*_*ana 4

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

或者

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

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

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);
}
Run Code Online (Sandbox Code Playgroud)

  • XPath 是一个有用的(也是行业标准的东西)。无需陷入 MS 特定的兔子洞,只需将 xml 加载到 XML 文档(例如,称为 doc)中,然后执行 XMLNode nodSKUDetails = doc.DocumentElement.SelectSingleNode(@"//SKUDetails"); (8认同)