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

后端 未结 6 1471
广开言路
广开言路 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:43

    I like @mads-hansen, his answer, so well that I wrote these general-purpose utility-class members:

        /// 
        /// Gets the  into a local-name(), XPath-predicate query.
        /// 
        /// Name of the child element.
        /// 
        public static string GetLocalNameXPathQuery(string childElementName)
        {
            return GetLocalNameXPathQuery(namespacePrefixOrUri: null, childElementName: childElementName, childAttributeName: null);
        }
    
        /// 
        /// Gets the  into a local-name(), XPath-predicate query.
        /// 
        /// The namespace prefix or URI.
        /// Name of the child element.
        /// 
        public static string GetLocalNameXPathQuery(string namespacePrefixOrUri, string childElementName)
        {
            return GetLocalNameXPathQuery(namespacePrefixOrUri, childElementName, childAttributeName: null);
        }
    
        /// 
        /// Gets the  into a local-name(), XPath-predicate query.
        /// 
        /// The namespace prefix or URI.
        /// Name of the child element.
        /// Name of the child attribute.
        /// 
        /// 
        /// This routine is useful when namespace-resolving is not desirable or available.
        /// 
        public static string GetLocalNameXPathQuery(string namespacePrefixOrUri, string childElementName, string childAttributeName)
        {
            if (string.IsNullOrEmpty(childElementName)) return null;
    
            if (string.IsNullOrEmpty(childAttributeName))
            {
                return string.IsNullOrEmpty(namespacePrefixOrUri) ?
                    string.Format("./*[local-name()='{0}']", childElementName)
                    :
                    string.Format("./*[namespace-uri()='{0}' and local-name()='{1}']", namespacePrefixOrUri, childElementName);
            }
            else
            {
                return string.IsNullOrEmpty(namespacePrefixOrUri) ?
                    string.Format("./*[local-name()='{0}']/@{1}", childElementName, childAttributeName)
                    :
                    string.Format("./*[namespace-uri()='{0}' and local-name()='{1}']/@{2}", namespacePrefixOrUri, childElementName, childAttributeName);
            }
        }
    

提交回复
热议问题