如何添加或给出一组用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。
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
您可以将呼叫识别节点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#