Thorin Oakenshield
Thorin Oakenshield

Reputation: 14692

How to check the existence of an element in an XML file using XML to LINQ in C#

The XML file have the following structure

<RootElement>
    <TestElement Count="10"/>
</RootElement>

I need to check the existence of "TestElement" and to read the attribute value of "Count" if it exists.

      Int32 Str = (XDocument.Load("Sample.xml").Descendants("<TestElement ")
                                               .Select(l_Temp => (Int32)l_Temp.Attribute("Count"))).ToList()[0];

For the above XML file this query is working properly.

But it throws an exception for the following cases.

Case 1

    <RootElement>
        <TestElement Count=""/>
    </RootElement>

Case 2

    <RootElement>
        <TestElement />
    </RootElement>

Case 3

    <RootElement>
    </RootElement>

Is there any idea to check the existence of an element or an attribute?

Upvotes: 1

Views: 1619

Answers (2)

bits
bits

Reputation: 8350

I guess in case of failure, you are expecting output value to be 0.

If that is the case, this would work in all situations:

        XDocument xdoc = XDocument.Load("../../Sample.xml");
        Int32 val = (from item in xdoc.Descendants("TestElement")
                     select (item.Attribute("Count") != null) ? Int32.Parse(item.Attribute("Count").Value) : 0).FirstOrDefault();

Upvotes: 3

Flesrouy
Flesrouy

Reputation: 684

Try this...

XElement TestElement = doc.Root.Elements().Where(element => element.Name.Equals("TestElement")).FirstOrDefault();

if (TestElement != null)
{
   XAttribute value = TestElement.Attributes().Where(attr => attr.Name.Equals("Count")).FirstOrDefault();
}

Upvotes: 3

Related Questions