2011-10-26 52 views
0

我正在嘗試將用戶名和密碼子項放入XML元素中。我希望它能夠在用戶輸入信息時檢查元素是否存在。如果是這樣,它會檢查它是否不同。如果不同,它會更新。如果它不存在,它會創建一個新的孩子。VB6 DomDocument更新節點/創建新節點

XML:

<ServersList> 
    <Server> 
     <ServiceName>Test Service</ServiceName> 
     <Url requestQuery="default">http://localhost</Url> 
     <DefaultLayers filter="off"></DefaultLayers> 
    </Server> 
</ServersList> 

由於有很多的服務器,我想搜索與服務名稱「測試服務」的服務器,然後進行檢查。

這是創建DOMDOCUMENT的VB代碼。

Dim xmlDocServers As DOMDocument 
Dim XMLFile As String 

XMLFile = projectpath & "\system\WMS_Servers.xml" 
If Not (ehfexist(XMLFile)) Then Exit Sub 

Set xmlDocServers = New DOMDocument 
xmlDocServers.async = False 
xmlDocServers.resolveExternals = False 
xmlDocServers.validateOnParse = False 

xmlDocServers.load XMLFile 

任何幫助將不勝感激!

非常感謝!

回答

2

最簡單的方法是利用XPATH來提取元素。 XPATH選擇器/ ServersList/Server [ServiceName/text()='myServiceName')將取出具有其文本與您的服務名稱相匹配的ServiceName子元素的所有Server元素。假設只有一個這樣的元素存在,selectSingleNode()將挑出與選擇器匹配的第一個元素。

如果你得到一個節點,那麼你應該做你的測試「差異」,不管是什麼。如果不同,那麼你應該以任何必要的方式更新它。如果沒有找到節點,那麼它會被創建,並且我認爲您還需要更新它。

記得在完成後調用xmlDocServers對象上的Save()!

Private Sub CheckServer(ByRef xmlDocServers As MSXML2.DOMDocument, ByRef serviceName As String) 

    Dim xmlService   As MSXML2.IXMLDOMElement 
    Dim updateOtherValues As Boolean 

    Set xmlService = xmlDocServers.selectSingleNode("/ServersList/Server[ServiceName/text()='" & serviceName & "']") 

    ' If nothing was returned, then we must create a new node. 
    If xmlService Is Nothing Then 
     Set xmlService = xmlDocServers.createElement("Server") 
     xmlService.Text = serviceName 
     xmlDocServers.documentElement.appendChild xmlService 
     updateOtherValues = True 
    Else 
     updateOtherValues = IsDifferent(xmlService) 
    End If 

    If updateOtherValues Then 
     DoUpdateOtherValues xmlService 
    End If 

End Sub 

Private Function IsDifferent(ByRef xmlService As MSXML2.IXMLDOMElement) As Boolean 
    IsDifferent = True 
End Function 

Private Sub DoUpdateOtherValues(ByRef xmlService As MSXML2.IXMLDOMElement) 
    ' 
End Sub