vb 如何操作xml文件

前端之家收集整理的这篇文章主要介绍了vb 如何操作xml文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


XML文件如下:

<?xml version="1.0" encoding="gb2312"?>
<testlist>
<test>
<id>1</id>
<name>自由飞翔</name>
<time>2007-12-7</time>
</test>
<id>2</id>
<name>自由</name>
</testlist>

    Dim XMLDoc As DOMDocument
    Dim root As IXMLDOMNode

    Dim xlst As IXMLDOMNodeList,xlst1 As IXMLDOMNodeList
    Dim xn As IXMLDOMNode
    Dim xnf As IXMLDOMNode
    Dim xe As IXMLDOMElement

    Set XMLDoc = New DOMDocument
    XMLDoc.Load "F:\example\test.xml"  'xml文件路径根据存放路径不同而不同!

    Set xn = XMLDoc.selectSingleNode("testlist")
    '以下为读取xml文件内容,这里用ListView控件显示
    Set xlst = xn.childNodes
    ListView1.ListItems.Clear
    For Each xnf In xlst
        Set xe = xnf
        Set xlst1 = xe.childNodes
        With ListView1.ListItems.Add(,xlst1.Item(0).Text)
            .SubItems(1) = xlst1.Item(1).Text
            .SubItems(2) = xlst1.Item(2).Text
        End With
    Next



    '以下是插入一个节点(这里插入一个id=3,name=飞翔,time=date 的节点)

    Dim XMLId As IXMLDOMElement
    Dim XMLName As IXMLDOMElement
    Dim XMLTime As IXMLDOMElement

    Dim returnValue As IXMLDOMNode

    Set xe = XMLDoc.createElement("test")    '创建一个<test>节点
    Set XMLId = XMLDoc.createElement("id")

    XMLId.Text = 3
    Set returnValue = xe.appendChild(XMLId)
    Set XMLName = XMLDoc.createElement("name")
    XMLName.Text = "飞翔"
    Set returnValue = xe.appendChild(XMLName)
    Set XMLTime = XMLDoc.createElement("time")
    XMLTime.Text = Date

    Set returnValue = xe.appendChild(XMLTime)
    Set returnValue = xn.appendChild(xe)    '添加到<testlist>节点中
    XMLDoc.save "F:\example\test.xml"



    '删除XML中id=2的节点

    Set xlst = XMLDoc.selectSingleNode("testlist").childNodes
    For Each xnf In xlst
        Set xe = xnf
        If xe.childNodes(0).Text = "2" Then
            xn.removeChild xe
        End If
    Next xnf
    XMLDoc.save "F:\example\test.xml"
原文链接:https://www.f2er.com/vb/259065.html

猜你在找的VB相关文章