简体   繁体   中英

How to read XML in C# using Xpath

I have this 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>

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

Manipulate XML data with XPath and XmlDocument (C#)

or

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.

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

as @Kirill Polishchuk answered - SKUDetails is defined in http://tempuri.org/

he shows you how to get using XDocument

you can use alsow XmlDocument like this:

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

SKUsDetails is defined in http://tempuri.org/ namespace. You can use this code to select SKUsDetails using XPath:

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

To select SKUDetails use: //a:SKUsDetails/a:SKUDetails

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM