Thursday, May 8, 2008

Working in XML in

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:

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

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")

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

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

Return xRoot
End Function

Public Shared Sub main(ByVal args() As String)
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: