Skip to content

Is There a Correct Structure for Your XML?

I recently had a customer ask about how to adjust XML structure and whether one format is better than another.

They had XML in this format:

<?xml version="1.0" encoding="UTF-8"?>
<xmldata>
  <row username="Mary" message="Welcome!" disable="NO"/>
</xmldata>

 

That XML was generated using code like this:

Dim xml As New XmlDocument

Dim root As XmlNode
root = xml.AppendChild(xml.CreateElement("xmldata"))

Dim row As XmlNode
row = root.AppendChild(xml.CreateElement("row"))
row.SetAttribute("username", "Mary")

Dim message As String = "Welcome!"
row.SetAttribute("message", message)

row.SetAttribute("disable", "NO")

Dim xmlText As String = xml.ToString

But because of a dependency on something else that used the XML they really wanted the XML to instead look like this:

<?xml version="1.0" encoding="UTF-8"?>
<xmldata>
  <username>Mary</username>
  <message>Welcome!</message>
  <disable>NO</disable>
</xmldata>

Since XML is always tricky, they were understandably confused about how to create the XML structure they needed. The trick here is that rather than creating the values as XML attributes they instead needed to be created as XMLTextNodes. Here is the code:

Dim xml As New XmlDocument

Dim root As XmlNode
root = xml.AppendChild(xml.CreateElement("xmldata"))

Dim snNode As XmlNode = root.AppendChild(xml.CreateElement("name"))
Dim snValue As XmlTextNode = xml.CreateTextNode("")
snValue.Value = "Mary"
snNode.AppendChild(snValue)

Dim message As String = "Welcome!"
Dim msgNode As XmlNode = root.AppendChild(xml.CreateElement("message"))
Dim msgValue As XmlTextNode = xml.CreateTextNode("")
msgValue.Value = message
msgNode.AppendChild(msgValue)

Dim disableNode As XmlNode = root.AppendChild(xml.CreateElement("disable"))
Dim disableValue As XmlTextNode = xml.CreateTextNode("")
disableValue.Value = "NO"
disableNode.AppendChild(disableValue)

Dim xmlText As String = xml.ToString

There really is no right or wrong XML format as both of these contain the same information. Sometimes it just comes down to preference or requirements from other software that may be using the XML. Fortunately, Xojo makes it possible to structure the XML any way you want.