0

Hi i am doing as follow

 XDocument xmlDoc = XDocument.Load(@"F:\test2.xml");
        var q = from c in xmlDoc.Descendants("autoivr.ok")
                where c.Element("LS_CZIP4").Value == "1234"
                select new
                {
                    name = c.Element("LS_LIN").Value,
                    state = c.Element("LS_STATE").Value                        
                };

When i use where c.attribute("LS_CZIP4").Value == "1234" i get error of object reference not set but when i use c.element there is no such error.

Following is the xml i made which is actually a table in sql converted to xml file

<?xml version="1.0" standalone="yes"?>
<DocumentElement>
   <autoivr.ok>
      <LS_LIN>abc</LS_LIN>
      <LS_STATE>def</LS_STATE>
      <LS_TYPE>5</LS_TYPE>
      <LS_CZIP4>1234</LS_CZIP4>
   <priority>0</priority>
   </autoivr.ok>

Can someone let me know the problem and how can i resolve and can i work with element tag only instead of attribute . Thank You

1 Answer 1

2

Use casting instead of accessing Value property. Casting to string will return null for non-existing elements. Getting Value will throw an exception

XDocument xmlDoc = XDocument.Load(@"F:\test2.xml");
var q = from c in xmlDoc.Descendants("autoivr.ok")
        where (string)c.Element("LS_CZIP4") == "1234"
        select new
        {
            name = (string)c.Element("LS_LIN"),
            state = (string)c.Element("LS_STATE")
        };

BTW you need closing tag for <DocumentElement>. Also LS_CZIP4 is element, not attribute. See the difference here XML Elements vs. Attributes.

Element: <LS_LIN>abc</LS_LIN>

Attribute: <autoivr.ok LS_LIN="abc">

6
  • Can you explain how LS_CZIP is element and not attribute here and is it ok to work with elements instead of attributes if we have to query the xml file
    – user959883
    Jan 16, 2013 at 9:53
  • @ffayyaz I've added example of LS_LIN as attribute and element. You should query for attribute if your item is an attribute in xml. If item is element, than query for element. Build your query based on xml structure. Jan 16, 2013 at 9:54
  • thanks so my xml structure is fine as i have a table named autoivr.ok and table has multiple columns and rows so every column in table is being represented as an element in xml file and so on .
    – user959883
    Jan 16, 2013 at 9:58
  • @ffayyaz actually I'd go with autroivrs as root element, with autoivr child elements for each row. But your current xml structure also will work. Jan 16, 2013 at 10:00
  • something like <autoivrs> <autoivr.fed_leg> elements </autoivr.fed_leg> <autoivr.fed_leg> elements </autoivr.fed_leg> </autoivrs>
    – user959883
    Jan 16, 2013 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.