我想在sub中放置一个if条件,告诉它在属性TEST =“test.doc”的xml节点STORE不存在时运行。任何建议都会很棒。我是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
<小时/> XML文件的示例
<city>
<store test="test.doc">
<books>
"New Words"
</books>
</store>
</city>
答案 0 :(得分:7)
假设 Location 是您要检查的节点,以查看您的属性是否存在:
If Location.Attributes.ItemOf("test") Is Nothing Then
'Attribute doesnt exist
Else
'Attribute does exist
End If
答案 1 :(得分:6)
尝试类似的东西:
If Not doc.SelectSingleNode("//store[@test='test.doc']") Is Nothing Then
Exit Sub
End If
答案 2 :(得分:1)
编辑:我的帖子试图回答@Judy提出的原始问题。它没有直接解决目前存在的问题(和标题)的高度修改版本。
您可以通过以下方式检查元素“存储”是否存在:
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
因此,您可以通过以下方式检查StoreNode中是否存在属性测试:
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
最后,您可以通过以下方式检查“Test”属性是否包含值“test.doc”:
If testAttribute.Value = "test.doc" Then
'The value matches.
End If
我确信您现在可以将这三个检查合并为一个块。我在这个明显冗长的解释中的目的是澄清这个概念。