thatthing
thatthing

Reputation: 676

How to parse multiple element attribute values in C#

I have below xml;

<Main>
    <Item ItemID="123456">
        <Devtm PL="SP"></Devtm>
        <Devtm PL="RV"></Devtm>
    </Item>
</Main>

I am trying to get all values belonging Devtm element. This element can have multiple values with PL attribute.

using (WebResponse response = request.GetResponse())
{
    using (StreamReader rd = new StreamReader(response.GetResponseStream()))
    {
        string soapResult = rd.ReadToEnd();
        var xdoc = XDocument.Parse(soapResult);
        var lineItemDetails = xdoc.Descendants("Main");

        foreach (var lineItemDetail in lineItemDetails)
        {
            var Devtm = lineItemDetail.Element("Item")?.Element("Devtm")?.Attribute("PL")?.Value;
            Console.WriteLine(Devtm);
        }
    }
}

This is only giving me first element value which is "SP". How can i get the second value as well? I don't need to loop because i know that there are only 2 values there.

LINQ is also not an option for some reasons. How can i achieve it with XDocument?

Upvotes: 1

Views: 190

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23258

You can rewrite your code a little bit to get an expected result. Use Descendants method to access an Item element and then iterate through its nodes

var lineItemDetails = xdoc.Root?.Descendants("Item");

foreach (var lineItemDetail in lineItemDetails?.Nodes().OfType<XElement>())
{
    var Devtm = lineItemDetail?.Attribute("PL")?.Value;
    Console.WriteLine(Devtm);
}

It prints SP and RV.

If you want to use index-based access, without loop, this can help

var lineItemDetails = xdoc.Root?.DescendantsAndSelf("Item").FirstOrDefault();
var nodes = lineItemDetails?.DescendantNodes().OfType<XElement>().ToList();

Console.WriteLine(nodes?[0]?.Attribute("PL")?.Value);
Console.WriteLine(nodes?[1]?.Attribute("PL")?.Value);

Upvotes: 1

Related Questions