1

Basically I'm trying to read settings from a XML file but I have all the nodes the same name that I'm using so I have to assign them ID's but how do I go about getting the node from the attribute ID and writing to that node I have just found

Here is what I have:

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

As you can see all I am doing is just getting the first node from the list without getting the node with attribute 1, 2, 3 etc. I just cant figure out how to get this and then use it to edit the node.

1 Answer 1

1

When you call xd.SelectNodes(nodePath), that nodePath argument can be any valid XPath. XPath provides all sorts of flexibility. In this case, you want to add a conditional clause which says you only want to select nodes by that name where they also contain an attribute by a certain name which equal a certain value. Here's an example of how you can express a condition like that in XPath:

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

In the above example, the document object is going to look for a MyRoot element in the root of the XML document. It's then going to find all of the MyElement elements which are direct children of that MyRoot element. It's then going to filter them to only include ones which contain an attribute called MyAttribute which equals MyValue. In other words:

<?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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.