How to give/add parent node for set of nodes in xmlDocument using vb.net or C#

好久不见. 提交于 2019-12-11 09:49:39

问题


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


来源:https://stackoverflow.com/questions/12048586/how-to-give-add-parent-node-for-set-of-nodes-in-xmldocument-using-vb-net-or-c-sh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!