tags:

views:

938

answers:

3

I would like to place an if condition within the sub that will tell it to run when the xml node STORE with attribute TEST="test.doc" does not exist. Any suggestions would be great. I'm new to vb.

Sub InsertNode(ByVal doc As XmlDocument)   
    Dim City As XmlNode = doc.DocumentElement

    Dim Location As XmlElement = doc.CreateElement("store")
    Location.SetAttribute("test", "test.doc")

    Dim books As XmlElement = doc.CreateElement("books")
    books.InnerXml = "New Words"
    Location.AppendChild(books)

    City.AppendChild(store)
End Sub 'InsertNode


Sample of the XML file

<city>
    <store test="test.doc">
        <books>
        "New Words" 
        </books>
    </store>
</city>
+2  A: 

Assuming that Location is the node you want to check to see if your attribute exists:

If Location.Attributes.ItemOf("test") Is Nothing Then
    'Attribute doesnt exist
Else
    'Attribute does exist
End If
Gavin Miller
A: 

Edit: My post attempts to answer the original question asked by @Judy. It does not directly address the highly modified version of the question (and the title) that exists at present.


You can check if an element "Store" exists in the following way :

Dim storeNode as XmlNode = doc.SelectSingleNode("Store")
If storeNode isnot Nothing Then
  'The "Store" node was found.
Else
  'The "Store" node was not found.
End If

Consequently, you can check if the attribute test exists in the StoreNode in the following way:

Dim testAttribute as XmlAttribute = CType(storeNode.Attributes.GetNamedItem("Test"),  XmlAttribute)

If testAttribute isnot nothing then
  'The "Test" attribute was found.
Else
  'The "Test" attribute was found.
End If

And finally, you can check if the "Test" attribute contains the value "test.doc" in the following way:

If testAttribute.Value = "test.doc" Then
  'The value matches.
End If

I'm sure you can now combine these three checks into a single block. My purpose in this obviously verbose explanation is to clarify the concept.

Cerebrus
+2  A: 

Try something like that :

If Not doc.SelectSingleNode("//store[@test='test.doc']") Is Nothing Then
    Exit Sub
End If
ybo
Thanks! Your statment really helped me out.
MG