<Example> <Items> <Item Id='0'>A</Item> <Item Id='1'>B</Item> <Item Id='2'>C</Item> <Item Id='3'>D</Item> <Item Id='4'>E</Item> <Item Id='5'>F</Item> <Item Id='6'>G</Item> </Items> <Items> <Item Id='10'>A1</Item> <Item Id='11'>B1</Item> <Item Id='12'>C1</Item> <Item Id='13'>D1</Item> <Item Id='14'>E1</Item> <Item Id='15'>F1</Item> <Item Id='16'>G1</Item> </Items> </Example>
What about to show to you is one of vb.net greatest tricks;- XML Literals
Using XML Literals we could just do
dim x= <Items> <Item Id='0'>A</Item> <Item Id='1'>B</Item> <Item Id='2'>C</Item> <Item Id='3'>D</Item> <Item Id='4'>E</Item> <Item Id='5'>F</Item> <Item Id='6'>G</Item> </Items> <Items> <Item Id='10'>A1</Item> <Item Id='11'>B1</Item> <Item Id='12'>C1</Item> <Item Id='13'>D1</Item> <Item Id='14'>E1</Item> <Item Id='15'>F1</Item> <Item Id='16'>G1</Item> </Items> </Example>
or we could use more power of the XML Literals;-
<%= %>
Which tells the compiler you are put a value (xmlnode) in here.
Edit: It allow you breaks out of the XML to include stuff derived through code.
Dim letters() = {"A", "B", "C", "D", "E", "F", "G"} Dim x1 = From i As Integer In Enumerable.Range(0, 7) _ Select <Item Id=<%= i %>><%= letters(i) %></Item> Dim x2 = From i As Integer In Enumerable.Range(0, 7) _ Select <Item Id=<%= i + 10 %>><%= letters(i) & "1" %></Item> Dim xb = <Example><Items><%= x1 %></Items><Items><%= x2 %></Items></Example>
or
Dim xb2 = <Example> <Items> <%= From i In Enumerable.Range(0, 7) Select <Item Id=<%= i %>><%= letters(i) %></Item> %> </Items> <Items> <%= From i In Enumerable.Range(0, 7) Select <Item Id=<%= i + 10 %>><%= letters(i) & "1" %></Item> %> </Items> </Example>
Now variable xb and xb2 have the same xml as x
I know it looks complex but it is an awful lot better then use XDocument & XElements.
Node Selection
Let get the Items Node
Dim ItemsNodes = xb.<Items>
You'll see that it also contains the Item nodes.
Notice the .< those means return all the child elements of this node, which have the same qualified name as contained in the angle brackets
Lets get all the Item nodes
Dim ItemNodes=xb...<Item>
Notice the ...< this means return all of the descendants elements which have the same qualified as contained in the angle bracket.
Node Attribute
Lets output the Id of ItemNodes(8)
Console.WriteLine("ItemNodes({0}) = {1}",8, ItemNodes(8)[email protected])
Notice the [email protected] which means an attribute.
We could change the Id value to 33 similarly
ItemNods(8)[email protected]=33
Conclusion
XML Literals + LINQ = Easy to manipulate XML.