xml 如何确定 XmlNode 是否具有特定属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/627089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 12:23:46  来源:igfitidea点击:

How do I determine if an XmlNode has a specific attribute?

xmlvb.net

提问by MG.

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 中放置一个 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>

回答by ybo

Try something like that :

尝试这样的事情:

If Not doc.SelectSingleNode("//store[@test='test.doc']") Is Nothing Then
    Exit Sub
End If

回答by Gavin Miller

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

假设Location是您要检查以查看您的属性是否存在的节点:

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

回答by Cerebrus

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.

编辑:我的帖子试图回答@Judy 提出的原始问题。它没有直接解决目前存在的问题(和标题)的高度修改版本。



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

您可以通过以下方式检查元素“Store”是否存在:

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:

因此,您可以通过以下方式检查 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

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

最后,您可以通过以下方式检查“Test”属性是否包含值“test.doc”:

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.

我相信您现在可以将这三个检查组合成一个块。我在这个明显冗长的解释中的目的是澄清这个概念。