2013-10-03 160 views
0

我有這個XML,它保留了TreeView中某些節點的名稱。 在我刪除TreeView中的節點後,我必須從XML文件中刪除節點。 我設法運行代碼來刪除節點配置文件2的內容,但我也想刪除父節點:「<Profile></Profile>」。用於刪除XML節點的代碼

請幫我用正確的代碼!

這些都是原來的節點:

<?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 

回答

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 
+0

它的工作。謝謝! – guest

+0

很高興聽到它亞歷克斯。請[接受我的回答](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 – nunzabar