tags:

views:

40

answers:

2

The XML file is having the following structure

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

i need to check the existance 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 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 existance of Element or attribute

Thanks in advance

+3  A: 

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();
}
Flesrouy
+3  A: 

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();
bits