How to add or give the parent node for set of nodes in xmlDocument using vb.net.
I am having following xml nodes
<books>
<title>title</title>
<isbn>123456</isbn>
<surname>surname</surname>
<givenname>givenname</givenname>
</books>
Now i want to add parent node <author>
for <surname>
and <givenname>
as follows.
<books>
<title>title</title>
<isbn>123456</isbn>
<author>
<surname>surname</surname>
<givenname>givenname</givenname>
</author>
</books>
can any one tell me how to do it in xmlDocument in vb.net.
You need to:
- Get the parent node that you want to modify (books).
- Add the new child element (author).
- Get the child elements you want to move (surname and givenname).
- For each node you want to move, remove it from it's parent node (books) and then add it as a child to the new parent node (author).
For instance:
Dim doc As New XmlDocument()
doc.Load(xmlFilePath)
Dim bookToModify As XmlNode = doc.SelectSingleNode("/books")
Dim author As XmlNode = doc.CreateElement("author")
bookToModify.AppendChild(author)
For Each node As XmlNode In bookToModify.SelectNodes("surname | givenname")
node.ParentNode.RemoveChild(node)
author.AppendChild(node)
Next
You can identify the nodes with a call to XPathSelectElements
, then remove them from the tree and add them to a new author
node.
Example:
Dim xml = <books>
<title>title</title>
<isbn>123456</isbn>
<surname>surname</surname>
<givenname>givenname</givenname>
</books>
Dim author = <author />
xml.Add(author)
For Each node in xml.XPathSelectElements("./givenname|./surname")
node.Remove()
author.Add(node)
Next