【问题标题】:How to read XML in C# using Xpath如何使用 Xpath 在 C# 中读取 XML
【发布时间】:2014-05-26 20:13:49
【问题描述】:

我有这个 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 读取 &lt;SKUDetails&gt; 节点?上述 XML 的 XNamespace 是什么?

【问题讨论】:

  • &lt;SKUDetails&gt; 里面的&lt;SKUsDetails&gt; 似乎有点模棱两可。

标签: c# xml .net-4.0


【解决方案1】:

Manipulate XML data with XPath and XmlDocument (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);
}

【讨论】:

  • XPath 是一个有用的(和行业标准的东西)。无需进入特定于 MS 的兔子洞,只需将您的 xml 加载到 XML 文档中(例如称为 doc),然后执行 XMLNode nodSKUDetails = doc.DocumentElement.SelectSingleNode(@"//SKUDetails");跨度>
【解决方案2】:

作为 @Kirill Polishchuk 回答 - SKUDetails is defined in http://tempuri.org/

他向你展示了如何使用XDocument

你也可以像这样使用XmlDocument

var dom = new XmlDocument();
dom.Load("data.xml");
var mgr = new XmlNamespaceManager(dom.NameTable);
mgr.AddNamespace("a", "http://tempuri.org/");
var res = dom.SelectNodes("//a:SKUDetails", mgr);

【讨论】:

    【解决方案3】:

    SKUsDetailshttp://tempuri.org/ 命名空间中定义。您可以使用此代码使用 XPath 选择 SKUsDetails

    var doc = XDocument.Load("1.xml");
    
    var mgr = new XmlNamespaceManager(doc.CreateReader().NameTable);
    mgr.AddNamespace("a", "http://tempuri.org/");
    
    var node = doc.XPathSelectElement("//a:SKUsDetails", mgr);
    

    要选择SKUDetails,请使用://a:SKUsDetails/a:SKUDetails

    【讨论】:

      猜你喜欢
      • 2011-02-18
      • 2013-05-27
      • 1970-01-01
      • 2016-03-14
      • 1970-01-01
      • 2011-12-21
      • 2011-12-25
      相关资源
      最近更新 更多