XML traversing using XmlDocument

前端 未结 2 674
不知归路
不知归路 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:

    <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]");
    
    0 讨论(0)
  • 2021-01-18 07:57

    Try this:

    private void btn_readXML_Click(object sender, EventArgs e)
    {
            var doc = new XmlDocument();
            doc.Load("e:\\contacts.xml");
    
            var nodes = xdoc.SelectNodes("//yournodename");
            // ex. 
            // var nodes = xdoc.SelectNodes("//Company");
            TraverseNodes(nodes);   
    }
    
    0 讨论(0)
提交回复
热议问题