使用LINQ读取XML元素
我想从使用LINQ的XML文件读取值。 这真的是我第一次尝试使用LINQ与普通的C#/ .Net方法。使用LINQ读取XML元素
我的XML看起来是这样的:
<Description>
<Account Green="A" White="D">House</Account>
<Account Green="B" White="D">Car</Account>
</Description>
这是我使用的LINQexpression。我想读House的价值,换句话说,属性A和D的元素。
var feeds = (from item in doc.Descendants("Description")
from category in item.Elements("Account")
let attribute = category.Attribute("Green")
let xAttribute = category.Attribute("White")
where attribute != null && (xAttribute != null && (xAttribute.Value == "A"
&& attribute.Value == "D")) select item.Value).ToString();
我弄不明白我做错了什么。 任何帮助表示赞赏。
您这里有一个IEnumerable<string>
- 你显然只想一个字符串这里,所以添加First()
让你列举的第一项的值:
var feeds = (from item in doc.Descendants("Description")
from category in item.Elements("Account")
let attribute = category.Attribute("Green")
let xAttribute = category.Attribute("White")
where attribute != null && (xAttribute != null && (xAttribute.Value == "A"
&& attribute.Value == "D")) select category.Value).First();
更简单的方法来达到同样的可能:
string result = doc.Descendants("Account")
.Where(x => x.Attribute("Green") != null && x.Attribute("Green").Value == "A"
&& x.Attribute("White") != null && x.Attribute("White").Value == "D")
.Select(x => x.Value)
.First();
@SaeedAmiri:不 - 'item.Value'已经是'string'类型了 – BrokenGlass 2012-04-27 21:17:02
但是这给了我GreenWhite。就像以前一样。 – user1017102 2012-04-27 21:21:34
@ user1017102:固定 - 需要选择'category.Value'而不是'item.Value' – BrokenGlass 2012-04-27 21:23:04
它是XmlElement还是XElement? – Gqqnbig 2017-03-13 23:22:07