4
votes

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 :

<?xml version="1.0" encoding="UTF-8" ?> 
<root>
    <automotive_industry>
        <automotive /> 
        <rail_global_services /> 
    </automotive_industry>
</root>

AND

<?xml version="1.0" encoding="UTF-8" ?> 
<root xmlns="http://www.my_department.my_company.com/project_name">
    <automotive_industry>
        <automotive /> 
        <rail_global_services /> 
    </automotive_industry>
    </root>

C# Code to select root node is as follows :

XmlDocument gazetteDocument = new XmlDocument();
gazetteDocument.Load(xmlFilePath);
XmlNodeList allNodes = gazetteDocument.SelectNodes("root");

This code works fine, it selects all the child nodes of root node when root node does not have any attribute that is, it works for 1st xml file but does not work for 2nd xml file because 2nd file has xmlns attribute.

Does anyone knows how to select all the child nodes of root node when root node has attributes??

EDIT : I found one XPath query : /* This query selects root node no matter whether it has any attribute or not. Once root node is selected, I can iterate through its all the child nodes .

3
possible duplicate of Using Xpath With Default Namespace in C#user357812
Reading that made me thought "maybe xml doesn't permit to have attributes especially on root node"...Sandburg

3 Answers

3
votes

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
votes

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
votes

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

XmlDocument gazetteDocument = new XmlDocument();
gazetteDocument.Load(xmlFilePath);
XmlNodeList allNodes = gazetteDocument.GetElementsByTagName("root");