Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML traversing using XmlDocument

Tags:

c#

.net

xml

I have the following code, which I use to traverse the XML:

private void btn_readXML_Click(object sender, EventArgs e)
{
        var doc = new XmlDocument();
        doc.Load("e:\\contacts.xml");
        // Load xml document.            
        TraverseNodes(doc.ChildNodes);     
}

static List<string> xmlnodes = new List<string>();
private static void TraverseNodes(XmlNodeList nodes)
{     
       foreach (XmlNode node in nodes)
       {                   
              List<string> temp = new List<string>();                  
              temp.Add("Node name: " + node.Name.ToString());
              XmlAttributeCollection xmlAttributes = node.Attributes;

              foreach (XmlAttribute at in xmlAttributes)
              {
                   temp.Add("  Atrib: " + at.Name + ": " + at.Value);
              }

               xmlnodes.AddRange(temp);
               TraverseNodes(node.ChildNodes);     
}

But my problem is, I don't want to traverse the whole document, I only want to traverse the node and subsequently its children which has an attribute 'X'. Please note that I don't know where the node is present. So basically what I have to do is, find out if the node exists ( it'll have the attribute 'X'. That's how I identify its the right node) if yes then fetch its children.

Can anyone help me out here? I'm pretty new to XMLs. Thanks is advance!

like image 491
Ekta Avatar asked Jun 24 '14 05:06

Ekta


1 Answers

Assuming your XML having following structure:

<Contacts>
   <Contact X="abc">
       <Child1></Child1>
   </Contact>

   <Contact X="def">
       <Child2></Child2>
   </Contact>
</Contacts>

Example code using XmlNode.SelectNodes:

var doc = new XmlDocument();
doc.Load("e:\\contacts.xml");

//get root element of document   
XmlElement root = doc.DocumentElement;
//select all contact element having attribute X
XmlNodeList nodeList = root.SelectNodes("//Contact[@X]");
//loop through the nodelist
foreach (XmlNode xNode in nodeList)
{       
    //traverse all childs of the node
}

For different XPath Queries see this link.

UPDATE:

If you want to select all elements having attribute X in the document. No matters where they exists. You could use following:

//select all elements in the doucment having attribute X
XmlNodeList nodeList = root.SelectNodes("//*[@X]");
like image 78
Hassan Avatar answered Sep 27 '22 20:09

Hassan