LINQ to XML - search Attribute substring

J

JY

Hi,

I'm using a query to find some elements in a XML document, based on an
attribute substring, but it throws a null exception in the code shown below:

static void Main(string[] args)
{
XElement root = XElement.Load("PurchaseOrders.xml");
IEnumerable<XElement> purchaseOrders =
from el in root.Elements("PurchaseOrder")
where
(from add in el.Descendants()
where
add.Attribute("MyAttribute").Value.Contains("ZXCV")
select add)
.Any()
select el;


foreach (XElement el in purchaseOrders)

Console.WriteLine((string)el.Attribute("PurchaseOrderNumber"));
}

It throws the exception in
add.Attribute("MyAttribute").Value.Contains("ZXCV")

Appreciate any help.

TIA,
SD
 
M

Martin Honnen

JY said:
I'm using a query to find some elements in a XML document, based on an
attribute substring, but it throws a null exception in the code shown below:

static void Main(string[] args)
{
XElement root = XElement.Load("PurchaseOrders.xml");
IEnumerable<XElement> purchaseOrders =
from el in root.Elements("PurchaseOrder")
where
(from add in el.Descendants()
where
add.Attribute("MyAttribute").Value.Contains("ZXCV")
select add)
.Any()
select el;


foreach (XElement el in purchaseOrders)

Console.WriteLine((string)el.Attribute("PurchaseOrderNumber"));
}

It throws the exception in
add.Attribute("MyAttribute").Value.Contains("ZXCV")

You would better show us your XML and tell us which Descendants elements
exactly you want to check for that attribute "MyAttribute". Your current
attempt

from add in el.Descendants()
where
add.Attribute("MyAttribute").Value.Contains("ZXCV")

probably fails as there are descendant elements of the "PurchaseOrder"
element that don't have an attribute "MyAttribute".

For instance if you have

<root>
<PurchaseOrder>
<baz />
<foo MyAttribute="bar"/>
</PurchaseOrder>
</root>

then that "baz" element does not have an "MyAttribute" attribute and
that way the access
add.Attribute("MyAttribute").Value
gives an exception.

So you either need to look only at certain descendant elements where you
know (maybe from a schema) that the MyAttribute attribute is always
present or you need to add a check

from el in root.Elements("PurchaseOrder")
where
(from add in el.Descendants()
where
add.Attribute("MyAttribute") != null
&&
add.Attribute("MyAttribute").Value.Contains("ZXCV")
select add)
.Any()
select el;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top