LINQ to XML:查询树的表达式,其中某些值是属性,其他值是节点值

时间:2010-04-15 08:33:07

标签: c# linq-to-xml

我正在尝试编写一个查询表达式来解析XML树,但没有太多运气。

树如下:

<item> 
    <itemInfo id="1965339" lang="en" key="title"> 
      <info>Octopuzzle&#xd;</info> 
    </itemInfo> 
    <itemInfo id="1965337" lang="en" key="longDescription"> 
      <info>&quot;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.&#xd;
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.&#xd;
Are you ready for the deep-sea puzzle adventure?&#xd;
&quot;&#xd;</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.&#xd;</info> 
    </itemInfo> 
</item>

我没有任何问题加载到XElement中。

我需要做的是分别获取lang的给定值的 title 简短描述长描述的值属性,在本例中为 en

有人可以帮忙吗? 感谢

1 个答案:

答案 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");
               };