Anoushka Seechurn
Anoushka Seechurn

Reputation: 2256

Getting the ChildNode name and its Value

I have an XML in the following format

<DBdestination>
    <val1>ANI</val1>
    <val2>DNIS</val2>
    <val3>Date</val3>
    <val4>Time</val4>
    <val5>ConnId</val5>
    <val6>UUID</val6>
    <val7>EmployeeId</val7>
    <val8>AgentDN</val8> 
</DBdestination>  

I need to obtain the name of the child of DBdestination and their values in a list(or something as such) as val1,val2,val3,val4..... and in another list ANI,DNIS......

I tried

var xdoc = XDocument.Load("C:/Users/xxx/Desktop/RCCM_TOOL/configRCCM.xml");
var units = xdoc.Descendants("DBdestination").Elements().ToArray();

But this gives me the whole of the tag as such.

How can I get my desired results ?

Upvotes: 2

Views: 145

Answers (2)

Victor Mukherjee
Victor Mukherjee

Reputation: 11025

var xdoc = XDocument.Load("C:/Users/xxx/Desktop/RCCM_TOOL/configRCCM.xml");
            var units = xdoc.Descendants("DBdestination").Elements();
            var tagnames = units.Select(u => u.Name.LocalName).ToArray();
            var values = units.Select(u => u.Value).ToArray();

You can go with dictionary if you look to access the values by the element names, like below:

        var xdoc = XDocument.Load("C:/Users/xxx/Desktop/RCCM_TOOL/configRCCM.xml");
        var units = xdoc.Descendants("DBdestination").Elements();
        var dictionary = new Dictionary<string, string>();
        foreach (var u in units)
        {
            dictionary.Add(u.Name.LocalName, u.Value);
        }

Thereafter you can access the values from the dictionary like below:

string value1=dictionary["val1"];

Upvotes: 1

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

You're very close:

xdoc.Descendants("DBdestination")
    .Elements()
    .Select(e => Tuple.Create(e.Name.ToString(), e.Value))
    .ToList()

That would give you a List<Tuple<string, string>>.

One other alternative would be this:

...
    .Select(e => Tuple.Create(e.Name, e.Value))
    .ToList()

and that would give you a List<Tuple<XName, string>>. The nice thing about that is the XName can be compared with the name val1 and not need the namespace whereas the ToString() will give you the fully-qualified name.


To handle the need to support .NET 3.5; let's do it this way:

xdoc.Descendants("DBdestination")
    .Elements()
    .Select(e => new
    {
        Name = e.Name,
        Value = e.Value
    })
    .ToList()

Upvotes: 1

Related Questions