rraallvv rraallvv - 8 months ago 38
C# Question

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

Say I have something like:

<property name="the property name" value="the value"/>
<property name="some other property name" value="other value"/>

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

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


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']")