在特定节点之后删除XML中的所有节点

时间:2014-08-25 11:58:26

标签: xml vb.net

您好我有如下XML。

<?xml version="1.0" encoding="utf-8"?>
-<Master> 
 <UserDetails>
  <UserName>Michael</UserName>
  <Password>Password</Password>
 </UserDetails>
 <Height>155</Height>
 <Weight>150lb</Weight> 
 <OtherDetails>
  <Phone>987654327</Phone>
  <Email>mich.int@ymail.com</Email>
 </UserDetails>
 <company>155</company>
 <address>155 beecroft</address>
</Master>

我的要求是删除HEIGHT <Height>节点下的所有节点。在HEIGHT <Height>应该从XML中删除后,无论有多少个节点 我的最终输出应该是。

<?xml version="1.0" encoding="utf-8"?>
-<Master> 
 <UserDetails>
  <UserName>Michael</UserName>
  <Password>Password</Password>
 </UserDetails>
 <Height>155</Height>
</Master>

请让我知道如何在VB.NET中完成它。

2 个答案:

答案 0 :(得分:1)

一种简单的方法是使用简单的For Each循环和标记,例如

Dim remove = False
For Each node in xml.<Master>.Elements.ToList()
    If remove Then node.Remove()
    If node.Name = "Height" Then remove = True
Next

While循环和NextNode(),例如

Dim node = xml.<Master>.<Height>(0).NextNode()
While node IsNot Nothing
    node.Remove()
    node = xml.<Master>.<Height>(0).NextNode()
End While

答案 1 :(得分:1)

使用XmlDocumentin case you still use that)的另一种可能方式:

Dim doc As New XmlDocument()
'load your xml here'
'select all nodes next to <Height> :'
Dim tobeDeleted = doc.SelectNodes("/Master/Height/following-sibling::*")
For Each node As XmlNode In tobeDeleted
    'remove each selected node :'
    node.ParentNode.RemoveChild(node)
Next