2010-06-28 138 views
0

說我有一些XML。如何使用VB獲取屬性值?如何獲取xml屬性值?

+0

也許你應該給予更多的細節?您現在如何加載XML,或者您現在是否在使用XML進行任何操作? – 2010-07-06 02:29:11

回答

3

假設您正在使用MSXML庫?

以下代碼將輸出子節點的所有屬性值。在這種情況下的XML是: -

<?xml version="1.0" encoding="utf-8"?> 
<documents> 
    <document id="12345" created="2002-09-24" owner="Andy" /> 
</documents> 

所以輸出結果會顯示id,created和owner的值。

下面的代碼: -

Dim XML As String 
    Dim objXML As New MSXML2.DOMDocument 
    Dim objElem As MSXML2.IXMLDOMElement 
    Dim objSub As MSXML2.IXMLDOMElement 

    XML = "<?xml version=""1.0"" encoding=""utf-8""?><documents><document id=""12345"" created=""2002-09-24"" owner=""Andy"" /></documents>" 

    If Not objXML.LoadXML(XML) Then 
     Err.Raise objXML.parseError.ErrorCode, , objXML.parseError.reason 
    End If 

    Set objElem = objXML.selectSingleNode("//documents") 

    For Each objSub In objElem.childNodes 
     Debug.Print objSub.nodeName 

     If objSub.Attributes.length > 0 Then 

     For i = 0 To objSub.Attributes.length - 1 

      Debug.Print objSub.Attributes(i).nodeName & " - " & objSub.Attributes(i).nodeValue 

     Next i 

     End If 

    Next