我如何在C#中执行此操作?

时间:2012-04-19 08:48:28

标签: c# xml vb.net xml-literals

以下单元测试在VB.Net中传递

<Test()> _
Public Sub VB_XMLLiteral_SyntaxRocks_Test()
    Dim XML = <Doc>
                  <Level1>
                      <Item id="1"/>
                      <Item id="2"/>
                  </Level1>
                  <Level1>
                      <Item id="3"/>
                      <Item id="4"/>
                  </Level1>
              </Doc>
    Assert.AreEqual(4, XML.<Level1>.<Item>.Count)
End Sub

如何在C#中声明相同的内容?

澄清一下,我想知道如何表达......

XML.<Level1>.<Item>

...在C#中

2 个答案:

答案 0 :(得分:3)

Assert.AreEqual(4, XML.Elements("Level1").Elements("Item").Count());

当然XML需要是XElement(这也是VB文字所产生的)

答案 1 :(得分:0)

使用LINQ to XML:

var XML = new XElement("Doc",
    new XElement("Level1",
        new XElement("Item", 
            new XAttribute("Id", 1)),
        new XElement("Item", 
            new XAttribute("Id", 2))),
    new XElement("Level1",
        new XElement("Item", 
            new XAttribute("Id", 3)),
        new XElement("Item", 
            new XAttribute("Id", 4))));

Assert.AreEqual(4, 
   (from element in XML.Elements("Level1").Elements("Item")
    select element).Count());