我正在尝试编写一个查询表达式来解析XML树,但没有太多运气。
树如下:
<item>
<itemInfo id="1965339" lang="en" key="title">
<info>Octopuzzle
</info>
</itemInfo>
<itemInfo id="1965337" lang="en" key="longDescription">
<info>"In Octopuzzle you play the Octopus on a mission! Escape the dangerous reef, and save it in the process. To do so you’ll have to make it through 20 challenging levels.
The game offers a real brain teasing levels packed with interactive sea creatures and objects that will keep you hooked for more. Along the way you’ll have shooting challenges, cannons to jump from, meet armoured fish, and many more surprises the deep-sea has to offer.
Are you ready for the deep-sea puzzle adventure?
"
</info>
</itemInfo>
<itemInfo id="1965335" lang="en" key="shortDescription">
<info>In Octopuzzle you play the Octopus on a mission! Escape the dangerous reef, and save it in the process. To do so you’ll have to make it through 20 challenging levels.
</info>
</itemInfo>
</item>
我没有任何问题加载到XElement中。
我需要做的是分别获取lang的给定值的 title ,简短描述和长描述的值属性,在本例中为 en 。
有人可以帮忙吗? 感谢
答案 0 :(得分:0)
当然,比如:
private string GetValue(XElement element, string language, string key)
{
return element.Elements("itemInfo")
.Where(x => (string) x.Attribute("lang") == language)
.Where(x => (string) x.Attribute("key") == key)
.Select(x => (string) x.Element("info"))
.FirstOrDefault();
}
...
string title = GetValue(item, "en", "title");
string longDescription = GetValue(item, "en", "longDescription");
string shortDescription = GetValue(item, "en", "shortDescription");
如果你已经有了相关的item元素,我认为你真的不想要一个查询表达式;如果你要查询多个元素,你可能会。例如:
var query = from item in doc.Descendants("item")
select new {
Title = GetValue(item, "en", "title"),
LongDescription = GetValue(item, "en", "longDescription"),
ShortDescription = GetValue(item, "en", "shortDescription");
};
或者以非查询表达形式:
var query = doc.Descendants("item")
.Select(item => new {
Title = GetValue(item, "en", "title"),
LongDescription = GetValue(item, "en", "longDescription"),
ShortDescription = GetValue(item, "en", "shortDescription");
};