Can't get XmlDocument.SelectNodes to retrieve any of my nodes?

前端 未结 4 1834
迷失自我
迷失自我 2020-12-28 08:09

I\'m trying to parse an XML document. The document in question is an AppxManifest file.

An example document looks like this:



        
相关标签:
4条回答
  • You might need to read this

    • http://msdn.microsoft.com/en-us/library/hcebdtae%28v=vs.90%29.aspx

    Here's your code:

    var xml = new XmlDocument();
    xml.Load("myXMLFile1.xml");
    var mgr = new XmlNamespaceManager(xml.NameTable);
    mgr.AddNamespace("", "http://schemas.microsoft.com/appx/2010/manifest");
    XmlNode root = xml.DocumentElement;
    var nodes = root.SelectNodes("//*[local-name()='Applications']/*[local-name()='Application']");
    
    0 讨论(0)
  • 2020-12-28 08:56

    Not in this particular case, but in general, if the namespace URN in the actual XML is not exactly the same as one used to add a namespace to a namespace manager (example: missing a trailing slash), and a prefix is specified in XPath, the query may return null.

    If namespace URN in the XML is not reliable, syntax

    "//*[local-name()='tag']" 
    

    will work.

    0 讨论(0)
  • 2020-12-28 09:04

    You need to specify prefixes for namespaces in NamespaceManager and XPaths. Note that prefixes does not need to match anything except between your XPath and your namespace manager*.

    var xml=new XmlDocument();
    xml.Load(myfile);
    var mgr=new XmlNamespaceManager(xml.NameTable);
    mgr.AddNamespace("a", "http://schemas.microsoft.com/appx/2010/manifest");
    mgr.AddNamespace("bar", "http://schemas.microsoft.com/developer/appx/2012/build");
    var nodes=xml.SelectNodes("//a:Applications", mgr);
    

    And as pointed out by other answers XPath that accepts any namespace is another option.

    *) I.e. in your particular sample there are 2 namespaces "default" (note that default prefix is not the same as empty namespace) and "build". So when you define your namespace manager you need to specify a prefix for each of the namespace (if you need to target nodes in both), but prefixes can be arbitrary strings (valid for prefixes but not empty). I.e. use "a" for "default" namespace and "bar" for namespace that mapped to "build" in the XML.

    0 讨论(0)
  • 2020-12-28 09:14

    You have to use xml namespace specifically to select them. consider

    "//*[local-name()='Applications']/*[local-name()='Application']"    
    

    in your case this code may also work well:

    var doc = new XmlDocument();
    doc.LoadXml(xml);
    var nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("a", "http://schemas.microsoft.com/appx/2010/manifest");
    var nodes = doc.SelectNodes("//a:Applications/a:Application",nsmgr);
    
    0 讨论(0)
提交回复
热议问题