Using Xpath With Default Namespace in C#

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

    For anyone looking for a quick hack solution, especially in those cases where you know the XML and don't need to worry about namespaces and all that, you can get around this annoying little "feature" by simply reading the file to a string and replacing the offensive attribute:

    XmlDocument doc = new XmlDocument();
    string fileData = File.ReadAllText(fileName);
    fileData = fileData.Replace(" xmlns=\"", " whocares=\"");
    using (StringReader sr = new StringReader(fileData))
    {
       doc.Load(sr);
    }
    
    XmlNodeList nodeList = doc.SelectNodes("project/property");
    

    I find this easier than all the other non-sense requiring a prefix for a default namespace when I'm dealing with a single file. Hope this helps.

提交回复
热议问题