How do I do this in C#?
-
01-06-2021 - |
Question
The following Unit Test passes in 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
How do I assert the same thing in C#?
To clarify, I 'd like to know how to express...
XML.<Level1>.<Item>
...in C#
Solution
Assert.AreEqual(4, XML.Elements("Level1").Elements("Item").Count());
And of course XML
needs to be an XElement
(that's what a VB literal produces too)
OTHER TIPS
Using 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());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow