CBC_NS CBC_NS - 2 months ago 10
Vb.net Question

Issue setting DocumentElement

I'm trying to set documentelement to what I want to be the root element. When i try to do so I get the following error
Property 'DocumentElement' is readonly. I suppose that makes sense. I'm currently trying to convert msxml to system.xml.

Public Function GetXmlAllHierarchyObjects(Optional ByVal blnHideDisabled As Boolean = False) As XmlDocument

Dim recHierarchy As Recordset
Dim strSql As String = ""
Dim xmlDoc As XmlDocument = New XmlDocument()
Dim xmlRoot As XmlElement
Dim xmlParent As XmlNode
Dim intHeight As Integer
Dim xmlHierarchy As XmlElement

xmlRoot = xmlDoc.CreateElement("Hierarchy")
xmlDoc.DocumentElement = xmlRoot ' Error occurs here
recHierarchy = GetAllHierarchyObjects(blnHideDisabled, True)

Do While Not recHierarchy.EOF
xmlParent = xmlDoc.selectSingleNode("//Object[@ID='" & CStrSafe(recHierarchy("ParentID")) & "']")
If xmlParent Is Nothing Then
xmlParent = xmlRoot
intHeight = 0
Else
intHeight = CIntSafe(xmlParent.SelectSingleNode("Height").InnerText) + 1
End If

xmlHierarchy = xmlDoc.createElement("Object")
xmlParent.appendChild(xmlHierarchy)

xmlHierarchy.SetAttribute("ID", recHierarchy("ObjectID").ToString())

xmlHierarchy.appendChild(xmlDoc.createElement("Height"))
xmlHierarchy.LastChild.InnerText = CStrSafe(intHeight)

xmlHierarchy.appendChild(xmlDoc.createElement("ParentID"))
xmlHierarchy.LastChild.InnerText = CStrSafe(recHierarchy("ParentID"))
xmlHierarchy.appendChild(xmlDoc.createElement("Name"))
xmlHierarchy.LastChild.InnerText = CStrSafe(recHierarchy("Name"))

recHierarchy.MoveNext()
Loop

CloseRecordset(recHierarchy)

GetXmlAllHierarchyObjects = xmlDoc

End Function

Answer

The document element isn't really the root node. It's a level above the root. So you add your root node as a child of this.

    Dim xmlDoc As XmlDocument = New XmlDocument()
    Dim xmlRoot As XmlElement = xmlDoc.CreateElement("Hierarchy")
    xmlDoc.AppendChild(xmlRoot)
    MsgBox(xmlDoc.OuterXml)