【发布时间】:2018-02-22 21:38:45
【问题描述】:
我想根据属性选择 xml 节点。我对 linq to xml 的工作方式非常陌生,并且无法编写正确的查询。我该如何解决?
我的 XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Enable0" value="true" />
<!-- dumb comment -->
<add key="Enable1" value="false" />
<!-- dumb comment1-->
<add key="Enable2" value="true" />
<add key="Enable3" value="false" />
<!-- dumb comment2 -->
<add key="Enable4" value="true" />
</appSettings>
<asdf>
<a key="b"></a>
<a key="c"></a>
<a key="d"></a>
</asdf>
</configuration>
我的尝试:
private string GetAttribute(string name)
{
//???
var query = from node in deafultElement.Elements("add")
where node.Attribute("key").Value == name
select node.Attribute("value").value;
return query.toString();
//currently returns "System.Linq.Enumerable+WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,System.String]"
}
【问题讨论】:
-
@mjwills 我将编辑并添加一些用于测试的示例 xml,但您还想要什么代码?我不确定哪些代码部分与这个问题相关。
-
您执行
select .Value,它将是一个字符串,而不是一个节点/元素。 -
@mjwills 然后我可以简单地删除所有代码并只显示那个损坏的查询。那会是个好选择吗?
-
不要使用 Value : (string)node.Attribute("key") & (string)node.Attribute("value") 如果对象不存在你会得到一个错误。
标签: c# linq-to-xml