如何给/在XmlDocument的使用vb.net或C#添加父节点的节点集合(How to give

2019-10-17 03:53发布

如何添加或给出一组用vb.net中的XmlDocument节点的父节点。

我有以下XML节点

<books>
   <title>title</title>
   <isbn>123456</isbn>
   <surname>surname</surname>
   <givenname>givenname</givenname>
</books>

现在,我想补充父节点<author><surname><givenname>如下。

 <books>
   <title>title</title>
   <isbn>123456</isbn>
   <author>
      <surname>surname</surname>
      <givenname>givenname</givenname>
   </author>
 </books>

任何一个可以告诉我怎么做它的XmlDocument在vb.net。

Answer 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


Answer 2:

您可以将呼叫识别节点XPathSelectElements ,然后从树中删除它们,并将它们添加到一个新author节点。


例:

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


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