How to read XML in C# using Xpath

后端 未结 3 747
耶瑟儿~
耶瑟儿~ 2020-12-06 12:18

I have this XML




        
相关标签:
3条回答
  • 2020-12-06 12:44

    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);
    }
    
    0 讨论(0)
  • 2020-12-06 12:51

    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

    0 讨论(0)
  • 2020-12-06 12:51

    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);
    
    0 讨论(0)
提交回复
热议问题