Search code examples
c#xpathxmldocument

Need to get values out of a very complex XML file in Windows Form C#


I have a dataGridview1 to which I want to add two columns and populate values from an XML file.

The values I need to extract values from XML File have tags: "Name", "Status" and "IP" . They are inside 'item' nodes.

I need to match the name from XML File to a dataGridview column (columnName) , and if matches, I need to put "Status" and "IP" , to the newly added column in dataGridView.

The XML File seems to be so complex for me to extract data. I cannot use the dataset, because it throws an error that 'item' is used within the nested table twice. I tried using Xpath, but I could not make the Xpath string required to get the data from XML.

Any help is welcome. Thank You.

Here is the link to the XML File from which I need data: https://net-perm.s3.amazonaws.com/test.xml

XmlDocument doc = new XmlDocument();
            doc.LoadXml(CUCMReply);
Int ColumnIndex;            //Known value
String ColumnName;          //Known value

                dataGridView1.Columns.Add(columnName + "RegisterStatus", columnName + "RegisterStatus"); 
                dataGridView1.Columns.Add(columnName + "IP", columnName + "IP");            

            

Solution

  • If you want to write an XPath expression, you could use (local-name() to circumvent namespace problems) :

    //*[local-name()="item"]/*[local-name()="Name"][contains(.,"columnName")]/following::*[local-name()="Status" and ancestor::*[2][local-name()="CmDevices"] or local-name()="IP"][position()<3]
    

    Where "columnName" is the value you have to match. For each match, it will output 2 nodes : Status and IP.