Imorian
Imorian

Reputation: 157

Parse xml by Xdocument

I have a simple xml file:

    <?xml version="1.0" encoding="utf-8" ?>
      <Parameters>
        <Valid>
          <SetSensorParameter>
            <param paramid="1" value_p="15" size="16"/>
            <param paramid="2" value_p="22" size="8"/>
          </SetSensorParameter>
       </Valid>
     </Parameters>

I need get values of attributes of :

    <param paramid="1" value_p="15" size="16"/>
    <param paramid="2" value_p="22" size="8"/>

I have next code for it:

    var doc = XDocument.Load(path);
    var smth = doc.Element("Parameters").Element("Valid").Element("SetSensorParameter").Nodes();

I get access to both param, but i can't get values of paramid, value_p, size.

How I can do it?

Upvotes: 0

Views: 197

Answers (3)

Imorian
Imorian

Reputation: 157

    var doc = XDocument.Load(path);
        var parameters = doc.Root
                .Element("Valid")
                .Element("SetSensorParameter")
                .Element("param");

I can use just

     var doc = XDocument.Load(path);
        var parameters = doc.Root
                .Element("Valid")
                .Element("SetSensorParameter")
                .Element("param").Attributes();

And after that

    parameters.ElementsAfterSelf.Attributes();

Sorry but my Visual Studio don't want to make foreach with parameters.

Upvotes: 0

w.b
w.b

Reputation: 11228

You can also get attribute values this way:

var attributes =  doc.Root.Descendants()
                     .Where(elem => elem.HasAttributes)
                     .SelectMany(e => e.Attributes());

foreach (var attr in attributes)
    Console.WriteLine("Name: {0}, value: {1}", attr.Name, attr.Value);

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499800

Rather than using Nodes, it would be simpler to use Elements, so that you can then use the Attribute method to retrieve each attribute:

var parameters = doc.Root
                    .Element("Valid")
                    .Element("SetSensorParameters")
                    .Elements("param");

foreach (var parameter in parameters)
{
    Console.WriteLine("{0}: {1} {2}",
                      (int) parameter.Attribute("paramid"),
                      (int) parameter.Attribute("value_p"),
                      (int) parameter.Attribute("size"));
}

Here the casts parse each of those attribute values as an int; similar conversions are available for other types.

Upvotes: 2

Related Questions