Home > Articles > Web Services > XML

  • Print
  • + Share This
From the author of

Helper Routines

Building and reading XML files is straightforward, but several operations require more than one step. To add a new node to an XML document, you need to create the node in the document, add it to its parent node, and then set its value. The MakeXmlNode routine shown in Listing 2 does all this in a nice package.

The program calls MakeXmlNode, passing it the node that should be the parent of the new node, the new node's name, and the new node's value. MakeXmlNode uses the parent node's OwnerDocument property to get a reference to the XmlDocument object that contains the parent node. If OwnerDocument returns Nothing, the parent node is actually the XmlDocument object itself.

MakeXmlNode then uses the document's CreateElement method to make a new node. It adds the node to the parent's collection of children with the AppendChild method. If the node's desired value is something other than Nothing, the routine saves it as the new node's value.

The ChildNodeValue function returns the value of a node's child. For example, consider this small XML file:


To get the X value, the program passes ChildNodeValue the parent node containing the MainForm tag. The function uses the parent's Item collection to select the child node—in this example, the node named X. If it does not find a child with the desired name, ChildNodeValue returns a default value. Otherwise, the function returns the child node's InnerText value. In this example, that value is 291.

Listing 2. These Routines Make Reading and Writing XML Data Easier

' Make and return a new XML node.
Public Function MakeXmlNode(ByVal parent As XmlNode, ByVal new_name As String, _
 Optional ByVal new_value As String = Nothing) As XmlNode
  Dim doc As XmlDocument
  Dim new_node As XmlNode

  ' Get the parent document.
  doc = parent.OwnerDocument
  If doc Is Nothing Then doc = parent

  new_node = doc.CreateElement(new_name)
  If Not (new_value Is Nothing) Then new_node.InnerXml = new_value

  Return new_node
End Function

' Return this node's child value.
Public Function ChildNodeValue(ByVal parent As XmlNode, ByVal value_name As String, _
 ByVal default_value As String) As String
  Dim child_node As XmlNode

  child_node = parent.Item(value_name)
  If child_node Is Nothing Then
    Return default_value
    Return child_node.InnerText
  End If
End Function
  • + Share This
  • 🔖 Save To Your Account