2011-10-10 28 views
3

給定以下XML。檢查xml節點是否不存在並執行某些操作而不是失敗

<?xml version="1.0" encoding="UTF-8"?> 
<xmldata> 
    <Products> 
     <ProductCode>M406789</ProductCode> 
     <ProductID>858</ProductID> 
     <ProductName>M406789 Ignition Box</ProductName> 
     <ProductDescriptionShort>&lt;img alt="" src="/v/vspfiles/assets/images/alliance_small.jpg" align="right" /&gt;Ignition Box</ProductDescriptionShort> 
     <ListPrice>134.2200</ListPrice> 
     <ProductPrice>80.5300</ProductPrice> 
     <SalePrice>59.9500</SalePrice> 
    </Products> 
</xmldata> 

這是腳本的相關部分。

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") 

如果加載上面的XML缺失和節點(可以說「SalePrice」),該腳本將失敗。我如何測試以查看節點是否存在,以便它不會失敗。過去我在Stack上看到過這樣的東西,但似乎無法找到它。

回答

8

設置充分利用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 
+0

雖然這工作我想在我的情況來決定,如果我想newpp給= 0或不予以定義與保羅的代碼。 – user357034

+1

將它保留爲未定義的唯一問題是,如果以後嘗試使用該變量(如果該類型的類型錯誤),則可能會發現其他錯誤。另一方面是,如果您處理的不僅僅是xml文檔,它可能會保留前一個循環的設置 - 因此將數據從其他產品實例中提取出來。它通常不會對事物進行初始化,因爲它往往會導致困難或晦澀的錯誤。 –

1

您可以在每次使用可變的時間只是做一個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 
0

就拿元素的列表:

Dim xmlNodeList As MSXML2.IXMLDOMNodeList 

Set xmlNodeList = xNewDoc.selectNodes("//ProductPrice") 

現在問列表的長度。如果零沒有。

debug.print xmlNodeList.length 
相關問題