Analytics


Google

Thursday, May 8, 2008

Working in XML in VB.net

The easiest way to create xml from scratch is to use the XMLDocument class.

All XML needs to have a root node. To do that, just declare a new XMLDocument class object and then use it to create the root node.

For example if you want to create the following xml:

<Book>
<Title>Programmer's Journal</Title>
<Author Name="Me" />
</Book>


You can write something like this:

Imports System.Xml

Public Class clsTest

Private Shared Function genXML() As XmlNode
Dim xRoot, xNode As XmlNode
Dim xAttr As XmlAttribute
Dim xDoc As New XmlDocument

xRoot = xDoc.CreateElement("Book")

Try
xNode = xDoc.CreateElement("Title")
xNode.InnerText = "Programmer's Journal"
xRoot.AppendChild(xNode)
xNode = xDoc.CreateElement("Author")
xAttr = xDoc.CreateNode(XmlNodeType.Attribute, "Name", xNode.NamespaceURI)
xAttr.Value = "Me"
xNode.Attributes.Append(xAttr)
xRoot.AppendChild(xNode)

Catch ex As Exception
Throw New Exception("[genXML01]" & ex.Message)
End Try

Return xRoot
End Function

Public Shared Sub main(ByVal args() As String)
Console.WriteLine(clsTest.genXML.OuterXml)
End Sub

End Class

Running the program above will generate an output like this:

<Book><Title>Programmer's Journal</Title><Author Name="Me" /></Book>


Note that you use XMLDocument.CreateElement to create each node and then append subsequent nodes to root node. The values within the tags are call innerText and then you can also get the whole xml by getting the OuterXML property from the root node. Values within the nodes are called attributes and is generated using XMLDocument.CreateNode and specifying the node type.

One gotcha, you can only append XMLNodes that are created from the same XMLDocument as child to the nodes.

No comments: