How do I use XPath with a default namespace with no prefix?

后端 未结 6 1473
广开言路
广开言路 2020-12-13 13:16

What is the XPath (in C# API to XDocument.XPathSelectElements(xpath, nsman) if it matters) to query all MyNodes from this document?



        
6条回答
  •  孤城傲影
    2020-12-13 13:53

    Here's an example of how to make the namespace available to the XPath expression in the XPathSelectElements extension method:

    using System;
    using System.Xml.Linq;
    using System.Xml.XPath;
    using System.Xml;
    namespace XPathExpt
    {
     class Program
     {
       static void Main(string[] args)
       {
         XElement cfg = XElement.Parse(
           @"
              
                
              
             ");
         XmlNameTable nameTable = new NameTable();
         var nsMgr = new XmlNamespaceManager(nameTable);
         // Tell the namespace manager about the namespace
         // of interest (lcmp), and give it a prefix (pfx) that we'll
         // use to refer to it in XPath expressions. 
         // Note that the prefix choice is pretty arbitrary at 
         // this point.
         nsMgr.AddNamespace("pfx", "lcmp");
         foreach (var el in cfg.XPathSelectElements("//pfx:MyNode", nsMgr))
         {
             Console.WriteLine("Found element named {0}", el.Name);
         }
       }
     }
    }
    

提交回复
热议问题