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

时间:2012-03-01 06:26:39

标签: 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>

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

3 个答案:

答案 0 :(得分:3)

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);
}

答案 1 :(得分:2)

{p> 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

答案 2 :(得分:2)

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

他向您展示了如何使用XDocument

你可以像这样使用alsow 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);