Using Xpath With Default Namespace in C#

前端 未结 13 1508
别那么骄傲
别那么骄傲 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:05

    I used the hacky-but-useful approach described by SpikeDog above. It worked very well until I threw an xpath expression at it that used pipes to combine multiple paths.

    So I rewrote it using regular expressions, and thought I'd share:

    public string HackXPath(string xpath_, string prefix_)
    {
        return System.Text.RegularExpressions.Regex.Replace(xpath_, @"(^(?![A-Za-z0-9\-\.]+::)|[A-Za-z0-9\-\.]+::|[@|/|\[])(?'Expression'[A-Za-z][A-Za-z0-9\-\.]*)", x =>
                    {
                        int expressionIndex = x.Groups["Expression"].Index - x.Index;
                        string before = x.Value.Substring(0, expressionIndex);
                        string after = x.Value.Substring(expressionIndex, x.Value.Length - expressionIndex);
                        return String.Format("{0}{1}:{2}", before, prefix_, after);
                    });
    }
    
    0 讨论(0)
提交回复
热议问题