2013-10-03 2 views
0

У меня есть этот XML, который сохраняет имя некоторых узлов в TreeView. После удаления узла в TreeView я должен удалить и узел из файла XML. Мне удалось запустить код для удаления содержимого узла Profile 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

Смежные вопросы