我在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作为字符串?我更希望使用一个变量,而不必将其分解为多个步骤。
发布于 2014-12-10 13:26:30
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();发布于 2014-12-10 13:33:49
即使不使用显式LINQ查询(对我来说更优雅),也可以获得该值,如下所示:
var value = your_XElement
.XPathSelectElement("Property[@name='IDValue2']")
.Attribute("value")
.Value;https://stackoverflow.com/questions/27402151
复制相似问题