VB 读取XML文件

   更新日期:2024.05.16

xml文本中属性值包含<>号没法读取,- 号可能也不行,符件里的文本修改了下。

你可以引用Microsoft XML, v6.0库,有几个版本,用new来建立xmlDocument对象,这可以获得点提示帮助。

下面代码把各个标签的属性值输出到立即窗口:

Private Sub Command1_Click()
    Dim xmldoc
    Set xmldoc = CreateObject("msxml2.domdocument")
    xmldoc.async = False
    xmldoc.Load "c:\xml.xml" '读取文件
    Dim transactionTag As Object '获取transaction标签
    Set transactionTag = xmldoc.Getelementsbytagname("transaction")(0)

    Debug.Print transactionTag.Attributes.getNamedItem("type").Text, transactionTag.Attributes.getNamedItem("vaultname").Text

    Dim documentTag As Object '获取document标签
    Set documentTag = transactionTag.childnodes(0)
    Debug.Print , documentTag.Attributes.getNamedItem("aliasset").Text, documentTag.Attributes.getNamedItem("pdmweid").Text

    Dim configurationTag As Object
    Dim attributeTag As Object
    Dim Attributes   As Object
    For Each configurationTag In documentTag.childnodes '遍历configuration标签
        Debug.Print , , configurationTag.Attributes.getNamedItem("name").Text, configurationTag.Attributes.getNamedItem("quantity").Text
        For Each attributeTag In configurationTag.childnodes '遍历attribute标签
            Set Attributes = attributeTag.Attributes
            Debug.Print , , , Attributes.getNamedItem("name").Text, Attributes.getNamedItem("value").Text
        Next
    Next
End Sub



Private Sub Command1_Click()
Dim xDoc As Object
Dim xmlFile As String
Dim strWidth As String
Dim strHeight As String
Set xDoc = CreateObject("MSXML2.DOMDocument")
xmlFile = "C:\aa.xml"
xDoc.Load xmlFile
strWidth = xDoc.selectSingleNode("overlays").selectSingleNode("Info").Attributes(2).Text
strHeight = xDoc.selectSingleNode("overlays").selectSingleNode("Info").Attributes(3).Text
MsgBox ("Width=" & strWidth & " Height=" & strHeight)
xDoc.selectSingleNode("overlays").selectSingleNode("Info").Attributes(2).Text = "123"
xDoc.selectSingleNode("overlays").selectSingleNode("Info").Attributes(3).Text = "456"
xDoc.save (xmlFile)
End Sub

注意 你上面的XML中Width="840"Height="630" 要分开,改成:
Width="840" Height="630"
满意请采纳。

解决思路:用java来读取xml内容,遇到<city_id>1</city_id>这个标签就保存到map中,然后把map的值跟option做一下映射就可以了。
具体读取xml的代码网上一大堆,最后遇到问题再来找我吧

相关链接

欢迎反馈与建议,请联系电邮
2024 © 视觉网