Using Xpath With Default Namespace in C#

前端 未结 13 1507
别那么骄傲
别那么骄傲 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 03:42

    First - you don't need a navigator; SelectNodes / SelectSingleNode should suffice.

    You may, however, need a namespace-manager - for example:

    XmlElement el = ...; //TODO
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(
        el.OwnerDocument.NameTable);
    nsmgr.AddNamespace("x", el.OwnerDocument.DocumentElement.NamespaceURI);
    var nodes = el.SelectNodes(@"/x:outerelement/x:innerelement", nsmgr);
    
    0 讨论(0)
  • 2020-11-22 03:43

    My answer extends the previous answer by Brandon. I used his example to create an extension method as follows:

    static public class XmlDocumentExt
    {
        static public XmlNamespaceManager GetPopulatedNamespaceMgr(this System.Xml.XmlDocument xd)
        {
            XmlNamespaceManager nmsp = new XmlNamespaceManager(xd.NameTable);
            XPathNavigator nav = xd.DocumentElement.CreateNavigator();
            foreach (KeyValuePair<string,string> kvp in nav.GetNamespacesInScope(XmlNamespaceScope.All))
            {
                string sKey = kvp.Key;
                if (sKey == "")
                {
                    sKey = "default";
                }
                nmsp.AddNamespace(sKey, kvp.Value);
            }
    
            return nmsp;
        }
    }
    

    Then in my XML parsing code, I just add a single line:

    XmlDocument xdCandidate = new XmlDocument();
    xdCandidate.Load(sCandidateFile);
    XmlNamespaceManager nmsp = xdCandidate.GetPopulatedNamespaceMgr();  // 1-line addition
    XmlElement xeScoreData = (XmlElement)xdCandidate.SelectSingleNode("default:ScoreData", nmsp);
    

    I really like this method because it is completely dynamic in terms of loading the namespaces from the source XML file, and it doesn't completely disregard the concept of XML namespaces so this can be used with XML that requires multiple namespaces for deconfliction.

    0 讨论(0)
  • 2020-11-22 03:43

    In my case adding a prefix wasn't practical. Too much of the xml or xpath were determined at runtime. Eventually I extended the methds on XmlNode. This hasn't been optimised for performance and it probably doesn't handle every case but it's working for me so far.

        public static class XmlExtenders
    {
    
        public static XmlNode SelectFirstNode(this XmlNode node, string xPath)
        {
            const string prefix = "pfx";
            XmlNamespaceManager nsmgr = GetNsmgr(node, prefix);
            string prefixedPath = GetPrefixedPath(xPath, prefix);
            return node.SelectSingleNode(prefixedPath, nsmgr);
        }
    
        public static XmlNodeList SelectAllNodes(this XmlNode node, string xPath)
        {
            const string prefix = "pfx";
            XmlNamespaceManager nsmgr = GetNsmgr(node, prefix);
            string prefixedPath = GetPrefixedPath(xPath, prefix);
            return node.SelectNodes(prefixedPath, nsmgr);
        }
    
        public static XmlNamespaceManager GetNsmgr(XmlNode node, string prefix)
        {
            string namespaceUri;
            XmlNameTable nameTable;
            if (node is XmlDocument)
            {
                nameTable = ((XmlDocument) node).NameTable;
                namespaceUri = ((XmlDocument) node).DocumentElement.NamespaceURI;
            }
            else
            {
                nameTable = node.OwnerDocument.NameTable;
                namespaceUri = node.NamespaceURI;
            }
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(nameTable);
            nsmgr.AddNamespace(prefix, namespaceUri);
            return nsmgr;
        }
    
        public static string GetPrefixedPath(string xPath, string prefix)
        {
            char[] validLeadCharacters = "@/".ToCharArray();
            char[] quoteChars = "\'\"".ToCharArray();
    
            List<string> pathParts = xPath.Split("/".ToCharArray()).ToList();
            string result = string.Join("/",
                                        pathParts.Select(
                                            x =>
                                            (string.IsNullOrEmpty(x) ||
                                             x.IndexOfAny(validLeadCharacters) == 0 ||
                                             (x.IndexOf(':') > 0 &&
                                              (x.IndexOfAny(quoteChars) < 0 || x.IndexOfAny(quoteChars) > x.IndexOf(':'))))
                                                ? x
                                                : prefix + ":" + x).ToArray());
            return result;
        }
    }
    

    Then in your code just use something like

            XmlDocument document = new XmlDocument();
            document.Load(pathToFile);
            XmlNode node = document.SelectFirstNode("/rootTag/subTag");
    

    Hope this helps

    0 讨论(0)
  • 2020-11-22 03:48

    Or, if anyone should be using an XPathDocument, like me:

    XPathDocument xdoc = new XPathDocument(file);
    XPathNavigator nav = xdoc.CreateNavigator();
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(nav.NameTable);
    nsmgr.AddNamespace("y", "http://schemas.microsoft.com/developer/msbuild/2003");
    XPathNodeIterator nodeIter = nav.Select("//y:PropertyGroup", nsmgr);
    
    0 讨论(0)
  • 2020-11-22 03:49

    In this case, it is probably namespace resolution which is the cause of the problem, but it is also possible that your XPath expression is not correct in itself. You may want to evaluate it first.

    Here is the code using an XPathNavigator.

    //xNav is the created XPathNavigator.
    XmlNamespaceManager mgr = New XmlNamespaceManager(xNav.NameTable);
    mgr.AddNamespace("prefix", "http://tempuri.org/");
    
    XPathNodeIterator result = xNav.Select("/prefix:outerelement/prefix:innerelement", mgr);
    
    0 讨论(0)
  • 2020-11-22 03:50

    You can use XPath statement without using XmlNamespaceManager like this:

    ...
    navigator.Select("//*[ local-name() = 'innerelement' and namespace-uri() = '' ]")
    ...
    

    That is a simple way of selecting element within XML with default namespace definied.

    The point is to use:

    namespace-uri() = ''
    

    which will found element with default namespace without using prefixes.

    0 讨论(0)
提交回复
热议问题