2014-01-10 222 views
1

我正在使用Visual Studio 2010並在VB中編碼。如何從節點列表中的節點獲取屬性?

我有一個由XML文件填充的ListBox。 我已經設法得到一個「全部刪除」的工作,但我無法設法讓「刪除單一」工作。不知道如何從節點列表中的節點獲取屬性值。 我需要將書籤元素的title屬性與包含listbox選定項目文本的lstBookmarks.Text相匹配。

突出顯示刪除需要發生的地方(至少對於我的代碼)。 只要解釋,我會很樂意接受完全重寫的代碼。

我的XML看起來像這樣

<Data> 
    <Bookmark title="Page 1" link="Some File Path Here" /> 
    <Bookmark title="Page 2" link="Some Other File Path Here" /> 
</Data> 

我刪除看起來像這樣

Private Sub DeleteToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles DeleteToolStripMenuItem.Click 

     If lstBookmarks.SelectedIndex = -1 Then 
      MessageBox.Show("There are no bookmarks to clear!") 
     ElseIf lstBookmarks.SelectedValue.ToString() = "" Then 
      MessageBox.Show("There are no bookmarks to clear!") 
     Else 
      Dim xmlFile As String = filePath & "Resources\bookmark.xml" 
      Dim XMLDoc As XmlDocument = New XmlDocument 
      Dim nodes As XmlNodeList 

      XMLDoc.Load(xmlFile) 
      nodes = XMLDoc.SelectNodes("Data") 

      Dim RootElement As XElement = XElement.Load(xmlFile) 
      Dim DataElement As XmlElement = XMLDoc.DocumentElement 
      Dim NewElement As XmlElement = XMLDoc.CreateElement("Bookmark") 
      Dim FindElement = RootElement.<Bookmark>.Attributes("title") 

      If DataElement.HasChildNodes Then 
       For Each Attribute In FindElement 
        If Attribute = lstBookmarks.Text Then 
         '************************************************ 
         'Match found, delete node or XML Element here 
         '************************************************ 
        Else 
         'No Match in XML, no need to delete 
        End If 
       Next 
      End If 
     End If 
    End Sub 

回答

1

要找到使用XmlDocument類的元素,你可以使用XPath做很容易,就像這樣:

Dim xPath As String = String.Format("/Data/Bookmark[@title='{0}']", lstBookmarks.Text) 
Dim theNode As XmlNode = XMLDoc.SelectSingleNode(xPath) 

或者,您可以使用XDocumentXElement類使用LINQ到這樣的XML:

Dim theElement As XElement = RootElement.<Bookmark>.First(Function(x) [email protected] = lstBookmarks.Text) 

或者:

Dim theElement As XElement = (From i As XElement 
           In RootElement.<Bookmark> 
           Where [email protected] = lstBookmarks.Text 
           Select i).First() 

您可以使用XPath來查找節點XDocument/XElement對象爲好。

+1

非常感謝。我能夠用你的第一個例子來完成我所需要的。然後我可以遍歷節點列表,然後執行node.RemoveChild(theNode)。 – xRuhRohx