簡體   English   中英

VB.Net XML從屬性獲取節點,然后寫入該節點

[英]VB.Net XML Getting Node from attribute then writing to that node

基本上,我試圖從XML文件中讀取設置,但是所有節點的名稱都與我相同,因此我必須為其分配ID,但是如何從屬性ID中獲取節點並寫入該節點我剛剛找到的節點

這是我所擁有的:

Public Sub write_xml_file(ByVal path As String, ByVal nodePath As String, ByVal innerText As String)
    If IO.File.Exists(path) = True Then

        ' Load the XmlDocument.
        Dim xd As New XmlDocument()
        xd.Load(path)

        Dim node As XmlNodeList = xd.SelectNodes(nodePath)

        If node IsNot Nothing Then
            Dim nodeId As Integer = 0
            For Each childNode As XmlElement In node
                MessageBox.Show(get_node_count(node))
                If childNode("p").InnerText = "" Then
                    MessageBox.Show("Found empty...")
                    Exit For
                Else
                    MessageBox.Show("Empty place not found, carry on looking...")
                    nodeId += 1
                    Continue For
                End If
            Next
        End If
        MessageBox.Show("Finished")
        ' Save the Xml.
        xd.Save(path)
    Else
        MessageBox.Show("Could not write to selected path: " + path)
    End If
End Sub

如您所見,我正在做的只是從列表中獲取第一個節點,而沒有獲得具有屬性1、2、3等的節點。我只是想不出如何獲取它,然后使用它來編輯該節點。

當您調用xd.SelectNodes(nodePath) ,該nodePath參數可以是任何有效的XPath。 XPath提供了各種靈活性。 在這種情況下,您需要添加一個條件子句,該條件子句表示您僅希望按該名稱選擇節點, 其中它們還包含具有與某個值相等的特定名稱的屬性 這是一個如何在XPath中表達類似條件的示例:

Dim node As XmlNodeList = xd.SelectNodes("/MyRoot/MyElement[@MyAttribute = 'MyValue']")

在上面的示例中,文檔對象將在XML文檔的根目錄中查找MyRoot元素。 然后它會找到所有的MyElement元素它們是直接孩子MyRoot元素。 然后,將對它們進行過濾,以僅包括那些包含名為MyAttribute的屬性,該屬性等於MyValue 換一種說法:

<?xml version="1.0" encoding="UTF-8"?>
<MyRoot>
  <MyElement>Will not be selected</MyElement>
  <MyElement MyAttribute="Wrong">Will not be selected</MyElement>
  <MyElement MyAttribute="MyValue">Will be selected</MyElement>
  <MyElement MyAttribute="MyValue">Will be selected</MyElement>
</MyRoot>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM