How to give/add parent node for set of nodes in xm

2019-07-26 17:53发布

问题:

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.

回答1:

You need to:

  1. Get the parent node that you want to modify (books).
  2. Add the new child element (author).
  3. Get the child elements you want to move (surname and givenname).
  4. 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


回答2:

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