获取xml属性的值作为字符串

时间:2014-12-10 13:24:01

标签: c# linq-to-xml

我在XElement中有一组xml,如下所示:

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

我希望将value属性值IDValue2作为字符串而不是XElement

我试过这样做:

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

以及其他一些不起作用的组合,并以XElement格式将其作为索引值列出。我想知道是否可以将单个值somevaluethatineed作为字符串?我最好希望使用一个变量,而不必将其分解为多个步骤。

2 个答案:

答案 0 :(得分:2)

XElement类提供Value属性。您可以使用它来获取与元素关联的文本:

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

您也可以按照string子句中的方式将属性转换为where

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

如果你知道元素中只有一个"IDValue2",你可以得到一个这样的字符串:

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

答案 1 :(得分:0)

即使没有明确的LINQ查询,你也可以获得该值(对我来说看起来更优雅),如下所示:

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