rraallvv rraallvv - 2 months ago 6
C# Question

Faster/shorter way to get an attribute's value in XElement with specified attribute in C#

Say I have something like:

<my-element>
<property name="the property name" value="the value"/>
<property name="some other property name" value="other value"/>
</my-element>


I'm using the following code to get "the value" from the property with name equal to "the property name".

string theValue = (
from p
in myElement.Elements("Property")
where p.Attribute("name").Value == "the property name"
select p.Attribute("value").Value
).FirstOrDefault();


This snippet does the job but I wonder whether there is a better way to do it.

L.B L.B
Answer

I am not sure about this subjective better way, but you can also use Xpath

var xDoc = XDocument.Parse(xmlstring);
var val = (string)xDoc.XPathSelectElement("//property[@name='the property name']")
                      .Attribute("value");
Comments