How to select xml root node when root node has attribute?

前端 未结 3 375
故里飘歌
故里飘歌 2020-12-21 03:41

I am trying to select all the child nodes of root node of an xml document using XPath query.

My xml file looks something like following :



        
相关标签:
3条回答
  • 2020-12-21 04:07

    Although the namespace in your XML document is fine, you need to use it in your SelectNodes. Use this code for your second XML:

    XmlDocument gazetteDocument = new XmlDocument();
    gazetteDocument.Load(xmlFilePath);
    XmlNamespaceManager nsmgr = new XmlNamespaceManager(gazetteDocument.NameTable);
    nsmgr.AddNamespace("ns", "http://www.my_department.my_company.com/project_name");
    XmlNodeList allNodes = gazetteDocument.SelectNodes("ns:root", nsmgr);
    

    The better way would be to use XDocument and corresponding classes. They are a lot easier to work with.

    0 讨论(0)
  • 2020-12-21 04:22

    You can use GetElementsByTagName method below are the snippet of my code

    XmlDocument gazetteDocument = new XmlDocument();
    gazetteDocument.Load(xmlFilePath);
    XmlNodeList allNodes = gazetteDocument.GetElementsByTagName("root");
    
    0 讨论(0)
  • 2020-12-21 04:31

    I don't know the old xml methods of C#, but you could always open the file to read as normal text, and then read to the first node and parse it however you like.

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