为什么我的查询返回属性的位置,而不是它们的值?

时间:2013-05-03 19:33:36

标签: c# xml winforms linq-to-xml

我正在读取xml文件并运行查询,查找“meetMark”= 1的任何条目,然后检查这些条目的“SUMMARY”元素,以获取“sum”和“number”属性。代码似乎正在正确地找到项目,因为输出显示了每个房间返回的'sum'和'number'的准确数量。但是,如何在不调用'.Value'的情况下返回属性的值。当我使用'.Value'它可以工作,除非有任何条目没有这些属性,然后我得到一个空异常。下面是我的代码和xml snip。

  List<string> test = new List<string>(); 

          var groups = from x in doc.Descendants("GROUP")
        where (string)x.Attribute("meetsMark") == "1"
        select x;

        foreach (var subgroup in groups)
        {
            //adds the code for any rooms found as 'ROOM: (Name)'
            test.Add("ROOM: " + (string)subgroup.Attribute("code") + Environment.NewLine);

            test.Add("ITEMS:" + Environment.NewLine);

            var sums = from summary in subgroup.Descendants("SUMMARY")
                       select summary;

            foreach (var sum in sums)
            {
                test.Add("sum = " + (string)subgroup.Attribute("sum"));
                test.Add("number = " + (string)subgroup.Attribute("number"));                                       
            }
            //add a blank line at the end to seperate each room
            test.Add(Environment.NewLine);                                
        }

        var message = string.Join(Environment.NewLine, test);
        MessageBox.Show(message);      

这是它正在阅读的xml。

<?xml version="1.0" encoding="utf-8"?>
<GROUP id="GRP1">
  <GROUP id="GRP2" code="MAIN" meetsMark="0">
    <GROUP id="GRP3" code="Room1" meetsMark="1">
      <ITEMS>
        <ITEM id="ITM6">
          <SUMMARY sum="Room1-Item1-Sum1" number="1"></SUMMARY>
        </ITEM>
        <ITEM id="ITM14">
          <SUMMARY sum="Room1-Item2-Sum1" number="2"></SUMMARY>
        </ITEM>
        <ITEM id="ITM15">
          <SUMMARY sum="Room1-Item3-Sum1" number="3"></SUMMARY>
        </ITEM>
        <ITEM id="ITM15">
          <SUMMARY sum="Room1-Item4-Sum1" number="4"></SUMMARY>
        </ITEM>
      </ITEMS>
    </GROUP>
    <GROUP id="GRP4" code="Room2" meetsMark="1">
      <ITEMS>
        <ITEM id="ITM95">
          <SUMMARY sum="Room2-Item1-Sum1" number="1"></SUMMARY>
        </ITEM>
        <ITEM id="ITM96">
          <SUMMARY sum="Room1-Item2-Sum1" number="2"></SUMMARY>
        </ITEM>
        <ITEM id="ITM97">
          <SUMMARY sum="Room1-Item3-Sum1" number="3"></SUMMARY>
        </ITEM>
      </ITEMS>
    </GROUP>
  </GROUP>
</GROUP>

它将返回房间,它将显示我正在查询的每个属性的位置,但不显示它们的值。如何获取这些值并避免因调用.Value并使其遇到没有与查询匹配的属性而导致的null异常问题?

1 个答案:

答案 0 :(得分:2)

我认为你的意思是:

foreach (var sum in sums)
{
    test.Add("sum = " + (string)sum.Attribute("sum"));
    //                          ^^^ not subgroup
    test.Add("number = " + (string)sum.Attribute("number"));
    //                             same
}