Linq to XML:从同名儿童和同名父母返回属性

时间:2010-11-20 03:35:38

标签: c# visual-studio-2010 linq-to-xml

那么,当天的noobie问题......

我有一个XML文件,结构如下:

<result>
  <rowSet name="name">
    <row name="name1" />
    <row name="name2" />
    <row name="name3" />
  </rowSet>
  <rowSet name="type">
    <row type="type1" />
    <row type="type2" />
    <row type="type3" />
  </rowSet>

etc..

</result>

我一直在尝试,而不是成功,从rowSet:属性名称获取单个rowSet的行属性。换句话说,我试图从“行”中提取属性,这些属性仅包含在rowSet:特定名称的属性下。

我尝试过使用:

    var rowSet = from rs in xmlDoc.Descendants("result")
                 where rs.Descendants("rowset").Attributes("name").Any(a => a.Value == "name")
                 select new
                 {
                     row = from r in xmlDoc.Descendants("row")
                           select new
                           {
                               skillID = r.Attribute("name"),
                           }
                 };

但是,这不会产生多于一个结果。相当令人沮丧,但又一次......在尝试了15种不同的建议之后,我一直无法记住读者的原始代码。

给出了答案:

var rowNames = (from i in xmlDoc.Descendants("rowSet")
                where (string)i.Attribute("name") == "name"
                select i.Descendants("row")) // Had to move this last ) to...
               .Select(r => (string)r.Attribute("name")); // Here in order to get it to work

我相信这有效,但是我太苛刻了,无法找到如何迭代它,即使我可以在程序运行时通过调试器的“结果视图”获取数据。


好的,所以我能够让该查询正确运行(首先移动“)”,当我开始单步执行代码时,rowNames中包含值。但是,我在以任何方式显示信息方面都非常失败。我在控制台应用程序中玩这个,fyi。

这是第一个问题。

第二个是,如果我开始通过向行元素添加多个属性来使我的XML更复杂,例如:

<result>
    <rowSet name="name">
        <row fName="Ted" lName = "Happy" />
        <row name="Billy" lName = "Maddison"/>
        <row name="John" lName = "Doe"/>
    </rowSet>
    <rowSet name="type">
        <row type="type1" type2 ="Hero"/>
        <row type="type2" type2 ="Villain" />
        <row type="type3" type2 ="Neutral"/>
    </rowSet>
</result>

如何检索元素中的所有属性?

这看起来很基本,这就是为什么我现在感觉很迟钝。

2 个答案:

答案 0 :(得分:0)

您可以轻松地单独获取名称:

var rowNames = from i in xmlDoc.Descendants("rowSet")
               where (string)i.Attribute("name") == "name"
               from r in i.Descendants("row")
               select (string)r.Attribute("name");

只需调整字符串即可获得另一个字符串。 (例如,您可以在方法中使用参数并使用参数。)

答案 1 :(得分:-1)

这有点猜测,但你的意思是:

from rs in xmlDoc.Descendants("result").Descendants("rowSet")
where (string)rs.Attribute("name") == "name"
from r in rs.Descendants("row")
select new { skillID = (string)r.Attribute("type") }