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!
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]");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With