检查 xml 节点是否不存在并执行某些操作而不是失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7714529/
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
check if xml node does not exist and do something instead of failing
提问by user357034
Given the following XML.
给定以下 XML。
<?xml version="1.0" encoding="UTF-8"?>
<xmldata>
<Products>
<ProductCode>M406789</ProductCode>
<ProductID>858</ProductID>
<ProductName>M406789 Ignition Box</ProductName>
<ProductDescriptionShort><img alt="" src="/v/vspfiles/assets/images/alliance_small.jpg" align="right" />Ignition Box</ProductDescriptionShort>
<ListPrice>134.2200</ListPrice>
<ProductPrice>80.5300</ProductPrice>
<SalePrice>59.9500</SalePrice>
</Products>
</xmldata>
This is the relevant part of a script.
这是脚本的相关部分。
Set xNewDoc = xData.responseXML 'ResponseXml returns DOMDocument object
Set ProductCode = xNewDoc.SelectSingleNode("//ProductCode")
Set ListPrice = xNewDoc.SelectSingleNode("//ListPrice")
x=Len(ListPrice.Text)
newlp = Left(ListPrice.Text,x-2)
Set ProductPrice = xNewDoc.SelectSingleNode("//ProductPrice")
x=Len(ProductPrice.Text)
newpp = Left(ProductPrice.Text,x-2)
Set SalePrice = xNewDoc.SelectSingleNode("//SalePrice")
x=Len(SalePrice.Text)
newsp = Left(SalePrice.Text,x-2)
Set ProductName = xNewDoc.SelectSingleNode("//ProductName")
If the above xml that is loaded is missing and of the nodes (lets say "SalePrice") the script will fail. How can I test to see if the node exists so it doesn't fail. I saw something on this on Stack in the past but can't seem to find it.
如果上面加载的 xml 丢失并且缺少节点(比如“SalePrice”),脚本将失败。我如何测试以查看节点是否存在,以便它不会失败。过去我在 Stack 上看到过有关此内容的内容,但似乎找不到。
回答by Jon Egerton
After setting getting a node from the XML, apply an Is Nothingcheck around the rest:
设置从 XML 获取节点后,Is Nothing对其余部分进行检查:
newpp = 0 'Initialize with a default value
Set ProductPrice = xNewDoc.SelectSingleNode("//ProductPrice")
If Not ProductPrice Is Nothing Then
x=Len(ProductPrice.Text)
newpp = Left(ProductPrice.Text,x-2)
End If
回答by Paul Graffam
You can just do an If Not ... Is Nothingcheck every time you use the variable, like so:
您可以在If Not ... Is Nothing每次使用变量时进行检查,如下所示:
Set ListPrice = xNewDoc.SelectSingleNode("//ListPrice")
If Not ListPrice Is Nothing Then
x=Len(ListPrice.Text)
newlp = Left(ListPrice.Text,x-2)
End If
Set ProductPrice = xNewDoc.SelectSingleNode("//ProductPrice")
If Not ProductPrice Is Nothing Then
x=Len(ProductPrice.Text)
newpp = Left(ProductPrice.Text,x-2)
End If
回答by PUshift
Take the element as a list:
将元素作为列表:
Dim xmlNodeList As MSXML2.IXMLDOMNodeList
Set xmlNodeList = xNewDoc.selectNodes("//ProductPrice")
Now ask for the length of the list. If zero there was none.
现在询问列表的长度。如果为零,则没有。
debug.print xmlNodeList.length

