XML traversing using XmlDocument

前端 未结 2 675
不知归路
不知归路 2021-01-18 07:46

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();         


        
2条回答
  •  走了就别回头了
    2021-01-18 07:53

    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]");
    

提交回复
热议问题