2014-01-10 5 views
1

Visual Studio 2010을 사용하고 VB에서 코딩하고 있습니다.nodelist의 노드에서 어떻게 속성을 가져 옵니까?

XML 파일로 채워진 ListBox가 있습니다. "모두 삭제"를 처리 할 수는 있지만 "단일 삭제"작업을 관리 할 수는 없습니다. nodelist의 노드에서 속성 값을 얻는 방법을 모릅니다. 북마크 요소의 title 속성과 목록 상자의 선택한 항목의 텍스트를 포함하는 lstBookmarks.Text를 일치시켜야합니다.

삭제가 필요한 곳에서 강조 표시됩니다 (최소한 내 코드는 해당). 설명 된대로 기꺼이 완전히 다시 작성된 코드를 허용합니다.

내 XML이 XmlDocument 클래스를 사용하여 요소를 찾으려면이

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

등이

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

내 삭제 외모처럼 보이는이 같은 XPath를 함께 그렇게 쉽게 수행 할 수 있습니다

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

또는 XDocument 또는를 사용하여 찾을 수 있습니다. 이 같은 XML로 LINQ를 사용하여 10 개 클래스 :

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() 

당신은뿐만 아니라 XDocument/XElement 객체의 노드를 찾기 위해 XPath를 사용할 수 있습니다.

+1

고맙습니다. 첫 번째 예제를 사용하여 내가 필요한 것을 정확하게 수행 할 수있었습니다. 그런 다음 노드 목록을 통해 반복 한 다음 node.RemoveChild (theNode)를 수행 할 수있었습니다. – xRuhRohx