0

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

  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 并使其命中没有与查询匹配的属性的条目而导致出现空异常问题?

4

1 回答 1

2

我想你的意思是:

foreach (var sum in sums)
{
    test.Add("sum = " + (string)sum.Attribute("sum"));
    //                          ^^^ not subgroup
    test.Add("number = " + (string)sum.Attribute("number"));
    //                             same
}
于 2013-05-03T19:41:45.870 回答