使用XmlDocument在同一元素中查找基于属性的属性

时间:2014-06-24 18:55:09

标签: xml xml-parsing

我希望通过基于一个属性“sequence”的元素循环,以检索另一个属性“stroke”。

我的xml如下:

    <tournament>
  <leaderboard>
    <player first_name="Jimmy" last_name="Walker" country="UNITED STATES" id="2db60f6e-7b0a-4daf-97d9-01a057f44f1d" position="1" money="900000.0" points="500.0" score="-17" strokes="267">
      <rounds>
        <round score="-1" strokes="70" thru="18" eagles="0" birdies="5" pars="9" bogeys="4" double_bogeys="0" other_scores="0" sequence="1"/>
        <round score="-2" strokes="69" thru="18" eagles="0" birdies="3" pars="14" bogeys="1" double_bogeys="0" other_scores="0" sequence="2"/>
        <round score="-9" strokes="62" thru="18" eagles="0" birdies="10" pars="7" bogeys="1" double_bogeys="0" other_scores="0" sequence="3"/>
        <round score="-5" strokes="66" thru="18" eagles="0" birdies="6" pars="11" bogeys="1" double_bogeys="0" other_scores="0" sequence="4"/>
      </rounds>
    </player>
</leaderboard>
</tournament>

我可以根据以下代码检索单个圆形元素:

//编辑反映解决方案

foreach (XmlNode player in doc.GetElementsByTagName("player"))
            {
                string strokes;
                dtAttributeList.Rows.Add(
                    player.Attributes["last_name"].Value,
                    player.Attributes["first_name"].Value,
                    player.Attributes["position"].Value,
                    player.Attributes["score"].Value);
                if (player.HasChildNodes)
                {
                    foreach (XmlNode round in player.LastChild)
                    {
                        strokes = round.Attributes["strokes"].Value;
                        dtAttributeList.Rows.Add(strokes);
                    }
                }
            }

然而,在这样做时,我只能检索第一个元素及其值。

请帮我找到一个解决方案,通过序列上的过滤器或某种循环来循环“圆”元素。

1 个答案:

答案 0 :(得分:1)

使用XPath比使用上面尝试的方法容易得多。您还使用for循环代替foreach创建了大量重复代码:

foreach (XmlNode player in doc.GetElementsByTagName("player"))
{
    string strokes;
    dtAttributeList.Rows.Add(
        player.Attributes["last_name"].Value,
        player.Attributes["first_name"].Value,
        player.Attributes["position"].Value, 
        player.Attributes["score"].Value);

    foreach (XmlNode round in player.SelectNodes("rounds/round"))
    {
        strokes = round.Attributes["strokes"].Value;
        dtAttributeList.Rows.Add(strokes);
    }
}

如果您需要根据sequence的顺序进行迭代(并且它们尚未按顺序排列),您可以执行以下操作:

var rounds = player.SelectNodes("rounds/round")
                   .OfType<XmlNode>()
                   .OrderBy(n => int.Parse(n.Attributes["sequence"].Value));
foreach (XmlNode round in rounds)
{
    // ...
}