0

我有这个 XML,它保留了 TreeView 中某些节点的名称。在 TreeView 中删除节点后,我还必须从 XML 文件中删除该节点。我设法运行代码来删除节点配置文件 2 的内容,但我还想删除父节点:“ <Profile></Profile>”。

请帮助我正确的代码!

这些是原始节点:

<?xml version="1.0" encoding="utf-8"?>
<Profiles>
  <Profile>
    <Profile_Name>Profile 1</Profile_Name>
    <Profile_Path>X:\Tests</Profile_Path>
  </Profile>
  <Profile>
    <Profile_Name>Profile 2</Profile_Name>
    <Profile_Path>X:\Tests</Profile_Path>
  </Profile>
</Profiles>

运行代码后,结果:

<?xml version="1.0" encoding="utf-8"?>
<Profiles>
  <Profile>
    <Profile_Name>Prof 1</Profile_Name>
    <Profile_Path>X:\Tests</Profile_Path>
  </Profile>
  <Profile>
  </Profile>
</Profiles>

这是使用的代码:

Public Sub DeleteXml()
    ProfileList.Load(xml_path)
    Dim nodes_list As XmlNodeList = ProfileList.SelectNodes("Profiles")
    Dim profile_node As XmlNode = ProfileList.SelectSingleNode("Profile")
    Dim profile_name_node As XmlNode = ProfileList.SelectSingleNode("Profile_Name")
    Dim bool As Boolean

For Each profile_node In nodes_list
            For Each profile_name_node In profile_node
                If EManager.TreeView1.SelectedNode.Text = profile_name_node.FirstChild.InnerText Then
                    bool = True                    
                Else
                    bool = False
                End If
                If bool = True Then
                    profile_name_node.RemoveAll()
                End If
            Next
        Next
    End Sub
4

1 回答 1

0

这可能不是最优雅的代码,但我刚刚对其进行了测试,它可以工作:

Public Sub DeleteXml()
    Dim profileList As New XmlDocument()
    profileList.Load("XmlFile1.xml")
    Dim profilesNode As XmlNode = profileList.SelectSingleNode("Profiles")
    Dim profiles As XmlNodeList = profilesNode.SelectNodes("Profile")
    For index As Integer = 0 To profiles.Count - 1
        Dim profile As XmlNode = profiles(index)
        If "Profile 2" = profile.FirstChild.InnerText Then
            profile.ParentNode.RemoveChild(profile)  
        End If
    Next
    profileList.Save("XmlFile2.xml")
End Sub
于 2013-10-03T19:37:26.693 回答