Reputation: 324
I have an XML document similar to the structure below. Using visual basic how can I insert nodes at the different levels depending on Id & Name.
does Xpath allow me to insert new nodes or does it only allow the modification of existing nodes?
so for example if I wanted to add <BuildingPart Id="B012" Name="Bedroom" Type="Room"/>
after "B011 Bathroom" how can this be achieved?
<Buildings>
<BuildingPart Id="B001" Name="House">
<BuildingPart Id="B002" Name="Level 1" Type="Level">
<BuildingPart Id="B003" Name="Kitchen" Type="Room"/>
<BuildingPart Id="B004" Name="Bedroom" Type="Room"/>
<BuildingPart Id="B005" Name="Lounge" Type="Room"/>
<BuildingPart Id="B006" Name="Bathroom" Type="Room"/>
</BuildingPart>
<BuildingPart Id="B007" Name="Level 2" Type="Level">
<BuildingPart Id="B008" Name="Bedroom" Type="Room"/>
<BuildingPart Id="B009" Name="Bedroom" Type="Room"/>
<BuildingPart Id="B010" Name="Study" Type="Room"/>
<BuildingPart Id="B011" Name="Bathroom" Type="Room"/>
</BuildingPart>
</BuildingPart>
</Buildings>
Thanks.
Upvotes: 1
Views: 3221
Reputation: 9888
Try this:
Dim doc As Xml.XmlDocument
Dim myNode As Xml.XmlNode
doc.Load(sFileName)
myNode = doc.GetElementById("B001").Clone()
myNode.Attributes("Id").Value = "B012"
myNode.Attributes("Name").Value = "Bedroom"
myNode.Attributes("Type").Value = "Room"
doc.GetElementById("B007").AppendChild(myNode)
EDIT:
To create the node from the begging without cloning simply:
myNode = doc.CreateElement("BuildingPart")
myNode.SetAttribute("Id", "B012")
myNode.SetAttribute("Name", "Bedroom")
myNode.SetAttribute("Type", "Room")
EDIT:
As seen in MSDN Documentation you need to specify always which element is the ID for an element in order to use GetElementById
:
The DOM implementation must have information which defines which attributes are of type ID. Although attributes of type ID can be defined in either XSD schemas or DTDs, this version of the product only supports those defined in DTDs. Attributes with the name "ID" are not of type ID unless so defined in the DTD. Implementations where it is unknown whether the attributes are of type ID are expected to return Nothing.
In order to do that, you can add at the beggining of your xml this code:
<!DOCTYPE Buildings[
<!ELEMENT BuildingPart ANY>
<!ATTLIST BuildingPart Id ID #REQUIRED>]>
If you cannot change the file, you have to loop through the elements and check the id from the attributte:
For Each elem As XmlElement In doc.GetElementsByTagName("BuildingPart")
If elem.GetAttribute("Id").Equals("B007") Then
elem.AppendChild(myNode)
Exit For
End If
Next
Upvotes: 2