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

本文关键字:字符串 xml 属性 获取 | 更新日期: 2023-09-27 18:33:46

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

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

我想将IDValue2value属性值作为字符串而不是XElement

我试过这样做:

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

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

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

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

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

您还可以按照在 where 子句中的方式强制转换属性以string

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();

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

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