Using Xpath With Default Namespace in C#

前端 未结 13 1513
别那么骄傲
别那么骄傲 2020-11-22 03:02

I\'ve got an XML document with a default namespace. I\'m using a XPathNavigator to select a set of nodes using Xpath as follows:

XmlElement myXML = ...;           


        
13条回答
  •  忘了有多久
    2020-11-22 04:02

    1] If you have a XML file without any prefix in the namespace:

    
    

    you have this workaround:

    XmlTextReader reader = new XmlTextReader(@"C:\Temp\books.xml");
    // ignore the namespace as there is a single default namespace:
    reader.Namespaces = false;
    XPathDocument document = new XPathDocument(reader);
    XPathNavigator navigator = document.CreateNavigator();
    XPathNodeIterator nodes = navigator.Select("//book");
    

    2] If you have a XML file with a prefix in the namespace:

    
    

    Use this:

    XmlTextReader reader = new XmlTextReader(@"C:\Temp\books.xml");
    XPathDocument document = new XPathDocument(reader);
    XPathNavigator navigator = document.CreateNavigator();
    XPathNodeIterator nodes = navigator.Select("//book");
    

    Of course, you can use a namespace manage if needed:

    XmlTextReader reader = new XmlTextReader(@"C:\Temp\books.xml");
    XPathDocument document = new XPathDocument(reader);
    XPathNavigator navigator = document.CreateNavigator();
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(reader.NameTable);
    nsmgr.AddNamespace("ns", "http://www.contoso.com/book");
    XPathNodeIterator nodes = navigator.Select("//book", nsmgr);
    

    I think that it's the easiest way to make the code working in the most cases.

    I hope this help to solve this Microsoft issue…

提交回复
热议问题