我有一个类似
的XML文件<?xml version="1.0">
<playlist>
<name>My Playlist</name>
<song>
<name>Song Name Here</name>
<path>Path to song here</path>
<note>Song notes here</note>
<artist>Song artist here</artist>
<type>Song type here</type>
</song>
<song>
<name>Song Name Here</name>
<path>Path to song here</path>
<note>Song notes here</note>
<artist>Song artist here</artist>
<type>Song type here</type>
</song>
</playlist>
我正在尝试从xml文件中删除歌曲节点,但我无法弄清楚我得到的错误的原因。我还在学习视觉基础知识。
错误:对象引用未设置为对象的实例。
这是我的代码
Private Sub MsItemRemoveClick(sender As System.Object, e As EventArgs) Handles msItemRemove.Click
If lvwPlaylist.SelectedItems.Count > 0 Then
Dim xmlDoc As New XmlDocument
xmlDoc.Load(_playlistpath & lblPlaylistName.Text & ".xml")
Dim songs As XmlElement = xmlDoc.SelectSingleNode("song")
For Each item As ListViewItem In lvwPlaylist.SelectedItems
For Each node As XmlElement In songs
If node.SelectSingleNode("name").InnerText = item.SubItems(0).Text Then
MsgBox(node.SelectSingleNode("name").InnerText) '<------ this is where the error pops up on 'node.ParentNode.RemoveAll()
End If
Next
item.Remove()
Next
xmlDoc.Save(_playlistpath & lblPlaylistName.Text & ".xml")
End If
End Sub
我的努力是遍历所有选定的列表视图项目,如果歌曲的名称与songs node
中的歌曲名称相匹配,则删除name
的父节点
答案 0 :(得分:1)
为清晰起见,删除了ListView ....
对于此XML文件......
<?xml version="1.0"?>
<playlist>
<name>My Playlist</name>
<song>
<name>Alpha song</name>
<path>Path to song here</path>
<note>Song notes here</note>
<artist>Song artist here</artist>
<type>Song type here</type>
</song>
<song>
<name>Beta song</name>
<path>Path to song here</path>
<note>Song notes here</note>
<artist>Song artist here</artist>
<type>Song type here</type>
</song>
<song>
<name>Charlie song</name>
<path>Path to song here</path>
<note>Song notes here</note>
<artist>Song artist here</artist>
<type>Song type here</type>
</song>
<song>
<name>Delta song</name>
<path>Path to song here</path>
<note>Song notes here</note>
<artist>Song artist here</artist>
<type>Song type here</type>
</song>
</playlist>
以C:\ Junk \ Junk1.xml保存在磁盘上,此代码将查找并删除两个中间节点......
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Dim strFilenameIn As String = "C:\Junk\Junk1.xml"
Dim strFilenameOut As String = "C:\Junk\Junk2.xml"
Dim lstNames As New List(Of String)
lstNames.Add("Beta song")
lstNames.Add("Charlie song")
Dim xmlDoc As New XmlDocument
xmlDoc.Load(strFilenameIn)
For Each strSongName As String In lstNames
Dim xnl As XmlNodeList = xmlDoc.SelectNodes("/playlist/song/name")
For i As Integer = xnl.Count - 1 To 0 Step -1
Dim xnd As XmlNode = xnl(i)
If xnd.FirstChild.Value = strSongName Then 'match'
xmlDoc.DocumentElement.RemoveChild(xnd.ParentNode)
End If
Next
Next strSongName
xmlDoc.Save(strFilenameOut)
MsgBox("Finished")
End Sub