patterncsharpMinor
Get XML elements with a particular attribute value
Viewed 0 times
elementswithxmlvaluegetattributeparticular
Problem
I have the following code to find xml elements that have a particular attribute value:
The problem is that if the element does not have that attribute, according to the docs, it will return null and we'll get a crash when we try to do
I've rewritten it like this:
But I think it's a bit ugly. Is there an idiomatic way of doing this - I imagine this is a fairly common operation? I suppose I could just do a regular loop.
IEnumerable elems =
xmlDoc.Descendants("elemName")
.Where(x =>
x.Attribute("attrName").Value
.Equals(
filename,
StringComparison.OrdinalIgnoreCase
)
);The problem is that if the element does not have that attribute, according to the docs, it will return null and we'll get a crash when we try to do
null.Value.I've rewritten it like this:
IEnumerable elems =
xmlDoc.Descendants("elemName")
.Where(x =>
((x.Attribute("attrName") == null)
? ""
: x.Attribute("attrName").Value).Equals(
filename,
StringComparison.OrdinalIgnoreCase
)
);But I think it's a bit ugly. Is there an idiomatic way of doing this - I imagine this is a fairly common operation? I suppose I could just do a regular loop.
Solution
I think you could use the null-conditional operator for
x.Attribute("attrName").Value and swap arguments of String.Equals to avoid the NullReferenceException as follows:IEnumerable elems =
xmlDoc.Descendants("elemName")
.Where(x =>
filename.Equals(
x.Attribute("attrName")?.Value,
StringComparison.OrdinalIgnoreCase
)
);Code Snippets
IEnumerable<XElement> elems =
xmlDoc.Descendants("elemName")
.Where(x =>
filename.Equals(
x.Attribute("attrName")?.Value,
StringComparison.OrdinalIgnoreCase
)
);Context
StackExchange Code Review Q#152282, answer score: 7
Revisions (0)
No revisions yet.