Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through XML Document

Tags:

c#

xml

My Method:


if (File.Exists( @"C:\config.xml"))
   {
    System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
    xd.Load( @"C:\config.xml");
    System.Xml.XmlElement root = xd.DocumentElement;
    System.Xml.XmlNodeList nl = root.SelectNodes("/config");
    foreach (System.Xml.XmlNode xnode in nl)
    {
        string name = xnode.Name;
        string value = xnode.InnerText;
        string nv = name + "|" + value;
        Send(nv);
        }

My Xml Doc

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<config>
<bla>D</bla>
<def>300</def>
<ttOUT>34000</ttOUT>
<num>3800</num>
<pw>help</pw>
<err>1</err>
....and so on
</config>

Now my method returns the first 2 and nothing else. What am i doing wrong...

like image 355
Josef Van Zyl Avatar asked Dec 06 '22 23:12

Josef Van Zyl


2 Answers

use the System.Xml namespace to avoid long type qualifications ie...

    using System.Xml;

Then try something like this..

    XmlNodeList nl = xd.SelectNodes("config");
    XmlNode root = nl[0];

    foreach (XmlNode xnode in root.ChildNodes)
    {
        string name = xnode.Name;
        string value = xnode.InnerText;
        string nv = name + "|" + value;
        Send(nv);
    }

I believe there is something wrong with your method.

a) I don't think SelectNodes should take the /config argument, rather it should take config.

b) After selecting the first (and only - XML files in .Net must have one and only one root node) root node you need to iterate through the ChildNodes of the root.

like image 146
El Ronnoco Avatar answered Dec 09 '22 12:12

El Ronnoco


root is the <config> tag, so I don't understand how root.SelectNodes("/config") should work at all. Use root.Childnodes instead.

like image 38
Jan Sverre Avatar answered Dec 09 '22 13:12

Jan Sverre