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();
Assuming your XML having following structure:
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]");