scapegoat17
scapegoat17

Reputation: 5821

Get value of xml attribute as string

I have a set of xml that i have in an XElement that looks like this:

<Object type="Item_Element">
  <Property name="IDValue1" value="somevaluethatihave"/>
  <Property name="IDValue2" value="somevaluethatineed"/>
  <Property name="IDValue3" value="somevaluethatihaveanddonotneed"/>
</Object>

I would like to get the value attribute value of IDValue2 as a string instead of as an XElement

I have tried doing so with this:

var meID = from el in linkedTeethInfo.DescendantsAndSelf("Property") 
    where (string)el.Attribute("name") == "IDValue2" 
    select el.Attribute("value");

As well as some other combinations that did not work and kept returning it in the XElement format listed as an index value. I was wondering if it would be possible to get the single value somevaluethatineed as a string? I would preferably like to have this using one variable and not have to break this down into multiple steps.

Upvotes: 2

Views: 1403

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

XElement class provides Value property. You can use it to get the text associated with the element:

IEnumerable<string> meID = from el in linkedTeethInfo.DescendantsAndSelf("Property") 
    where (string)el.Attribute("name") == "IDValue2" 
    select el.Attribute("value").Value;

You could also cast your attribute to string the way you did in the where clause:

IEnumerable<string> meID = from el in linkedTeethInfo.DescendantsAndSelf("Property") 
    where (string)el.Attribute("name") == "IDValue2" 
    select (string)el.Attribute("value");

If you know that there is only one "IDValue2" among the elements, you can get a single string like this:

string meID = (from el in linkedTeethInfo.DescendantsAndSelf("Property") 
    where (string)el.Attribute("name") == "IDValue2" 
    select el.Attribute("value").Value).FirstOrDefault();

Upvotes: 2

Andrey Korneyev
Andrey Korneyev

Reputation: 26846

You can get that value even without explicit LINQ query (and it looks more elegant for me) like this:

var value = your_XElement
    .XPathSelectElement("Property[@name='IDValue2']")
    .Attribute("value")
    .Value;

Upvotes: 0

Related Questions