十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
万事俱备,我们先用VB和MSXML的COM接口的DOM实现的一个例子来对XML操作进行初步的了解吧。首先声明下面要用的几个对象的变量:Dim tempdoc As DOMDocument
创新互联服务项目包括成县网站建设、成县网站制作、成县网页制作以及成县网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,成县网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到成县省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!
Dim tempnode As IXMLDOMNode
Dim tempelement As IXMLDOMElement
Dim tempattribute As IXMLDOMElement
Dim root As IXMLDOMElement文档对象模型(DOM)使用了一系列相应的对象描述了XML文档的等级状态,DOMDocument类是一个描绘XML文档的DOM结构的MSXML类。DOMDocument类仅仅提供了很少的几个有用的属性和方法,例如:Load方法载入一个xml文件,loadxml方法将字符串作为xml数据添加到对象中。DOMDocument的xml属性返回文档的xml描述,可以显示这些返回值看看这些文档究竟是什么样子,也可以将它存储为一个文件,DOMDocument对象的documentElement属性表示文档数据的根结点,通常情况下操作XML文档都从这里开始。DOMDocument提供了几种创建新节点的方法。CreateElement方法为文档创建一个新的元素节点,其他创建节点的方法有createAttribute, createProcessingInstruction, 和 createTextNode,在这里就不一一介绍了。IXMLDOMNode类描述了一个节点,该类提供了一系列用于搜索和操纵XML文档的属性和方法。selectSingleNode 方法用于搜索指定节点的后代,用于搜索指定节点路径的语言称为XPATH,XPATH非常棘手,本文就不详细说明其规范了。在IXMLDOMNode对象中,有许多有用的属性值:attributes.节点属性集合
nodeName.节点的标记名
nodeTypeString.节点的类型
ownerDocument.返回DOMDocument对象包含的节点
text.表示节点包含的文本内容。如果该节点包含其他节点,那么text代表了所有节点的文本内容的组合。
xml.给出了节点的xml内容,例如:"<Email>hongwanfu@yahoo.com</Email>".ChildNodes集合包含了节点的子节点。要给节点增加一个子节点,首先必须给使用DOMDocument对象的节点创建方法,然后将这个新建的节点加入到父节点的childNodes集合中。 ChildNodes集合包含了节点的子节点。要给节点增加一个子节点,首先必须给使用DOMDocument对象的节点创建方法,然后将这个新建的节点加入到父节点的childNodes集合中。由于每个节点类型都有不同的访问方法和内容限制,有时候使用特定类型的节点要比使用通用 IXMLDOMNode 对象更容易。要做到这一点,需要使用 IXMLDOMElement 对象来处理 XML 数据元素和属性。正如元素可以包含 XML 数据文件中的子元素、文本、注释、处理说明、CDATA 部分和实体引用一样,IXMLDOMElement 对象也可以包含 IXMLDOMElement、IXMLDOMText、IXMLDOMComment、IXMLDOMProcessingInstruction、IXMLDOMCDATASection 和 IXMLDOMEntityReference 对象。可以通过使用 IXMLDOMElement 对象的 getAttribute 和 setAttribute 方法来访问属性;或者通过 IXMLDOMElement 对象的 attributes 属性,将属性作为 IXMLDOMNamedNodeMap 对象进行管理。有关使用这些方法和对象的详细信息,请参阅 MSXML 4.0 SDK Help。接下来我们要做的是生成一个XML DOMDocument 对象 :Set tempdoc = New DOMDocument生成根节点并把它设置为文件的根 :Set root = tempdoc.createElement("Personal")
Set tempdoc.documentElement = root生成孩子节点添加到根节点上去,并且为这个节点设置一个属性 :
Set tempnode = tempdoc.createNode(NODE_ELEMENT, "Web", "")
tempnode.Text = " "
root.appendChild tempnode取得元素节点的接口,添加属性:Set tempelement = tempnode
tempelement.setAttribute "Type", "Homepage"最后,写XML文件:Open "CreateXMLFile.xml" for output as #1
Print #1, root.XML
Close #1下面就是上面程序生成的CreateXMLFile.xml文件的内容如图:首先,建立一个名叫Personal.xml的文件:<?xml version="1.0" encoding="GB2312"?><个人信息><姓名>洪万福</姓名><性别>男</性别><出生日期>1983年x月x日</出生日期><地址>福建省厦门市集美大学水产学院新区270#</地址><邮编>361021</邮编><QQ>24948251</QQ><个人主页> </个人主页></个人信息>其中,encoding="GB2312"是为了防止显示中文时出现乱码。接着,进入Visual Basic 6,建立7个Label和7个TextBox, 具体如图: 随后,编写如下代码:Option Explicit
Private p_AppPath As String
Private Sub Form_Load()
' 获得程序运行目录
p_AppPath = App.Path
If Right$(p_AppPath, 1) <> "\" Then p_AppPath = p_AppPath "\"
' 加载值
LoadValues
End SubPrivate Sub Form_Unload(Cancel As Integer)
' 保存现有的值
SaveValues
End SubPrivate Sub LoadValues() Dim xml_document As DOMDocument Dim values_node As IXMLDOMNode ' 载入文件 Set xml_document = New DOMDocument
xml_document.Load p_AppPath "Personal.xml"
If xml_document.documentElement Is Nothing ThenExit Sub End If '寻找节点
Set values_node = xml_document.selectSingleNode("个人信息")
' 读取各个节点的值
txtName.Text = GetNodeValue(values_node, "姓名", "???")
txtSex.Text = GetNodeValue(values_node, "性别", "???")
txtBirthday.Text = GetNodeValue(values_node, "出生日期", "???")
txtAddress.Text = GetNodeValue(values_node, "地址", "???")
txtZip.Text = GetNodeValue(values_node, "邮编", "???")
txtQQ.Text = GetNodeValue(values_node, "QQ", "???")
txtHomepage.Text = GetNodeValue(values_node, "个人主页", "???")End Sub' 返回各个节点的值Private Function GetNodeValue(ByVal start_at_node As IXMLDOMNode, ByVal node_name As String, _Optional ByVal default_value As String = "") As String Dim value_node As IXMLDOMNode
Set value_node = start_at_node.selectSingleNode(".//" node_name)
If value_node Is Nothing Then
GetNodeValue = default_value
Else
GetNodeValue = value_node.Text
End IfEnd Function' 保存现有的值Private Sub SaveValues()
Dim xml_document As DOMDocument
Dim values_node As IXMLDOMNode
' 建立XML文件
Set xml_document = New DOMDocument
Set values_node = xml_document.createElement("个人信息")
xml_document.appendChild values_node
CreateNode values_node, "姓名", txtName.Text
CreateNode values_node, "性别", txtSex.Text
CreateNode values_node, "出生日期", txtBirthday.Text
CreateNode values_node, "地址", txtAddress.Text
CreateNode values_node, "邮编", txtZip.Text
CreateNode values_node, "QQ", txtQQ.Text
CreateNode values_node, "个人主页", txtHomepage.Text
' 保存XML文件
xml_document.save p_AppPath "Personal.xml"
End SubPrivate Sub CreateNode(ByVal parent As IXMLDOMNode, _ByVal node_name As String, ByVal node_value As String) Dim new_node As IXMLDOMNode
Set new_node = parent.ownerDocument.createElement(node_name)
new_node.Text = node_value
parent.appendChild new_node
End Sub运行结果如下: 虽然,MSXML提供了从Visual Basic6.0加载和存储XML文档的工具,但是,对其的应用要求程序员对VB和MSXML的COM接口有一定的认识,所以,并不是得到很广泛的应用。
作者:洪万福出处:微软社区责任编辑: 方舟 [ 2003-08-20 10:45 ] 本文为计划将应用程序更新到VB.NET的VB开发用户提供一些关于XML的建议 Visual Basic.NET的出现大大改变了这个状况,Visual Basic.NET提供了使用XML、XSL以及其他XML工具的完整工具,使用户很轻松就能实现XML的应用,甚至,在不用编写代码的情况下操作XML。ADO.NET是Microsoft新推出的.NET框架中用于数据访问的组件,其最大的优点就是使用XML作为传送数据的标准,只要有一个XML文本,就可以读入ADO.NET的组件中,然后ADO.NET再以XML格式传给数据库或者其他组件。可以使用DataSet对象的ReadXML方法将一个XML文件读入到DataSet中,这是一个重载的方法,有几种语法格式,经常用到的如下所示:ReadXML(FileName)其中,FileName为XML文档的名字,现在将前面创建的XML文本“Personal.xml”读入到DataSet中。新建一个项目,在窗体上创建一个Button和一个DataGrid控件,双击Button1输入以下代码:Dim ds As New DataSet()'读入XML文档
ds.ReadXml("personal.xml")
Dim tb As DataTable
Dim dv As DataView
tb = ds.Tables(0)
dv = New DataView(tb)
Me.DataGrid1.DataSource = dv
使用System.XML
Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Xml
namespace HowTo.Samples.XML
public class WriteXmlFileSample
private const document as string = "newbooks.xml"
shared sub Main()
Dim myWriteXmlFileSample as WriteXmlFileSample
myWriteXmlFileSample = new WriteXmlFileSample()
myWriteXmlFileSample.Run(document)
end sub
public sub Run(args As String)
Dim myXmlTextReader as XmlTextReader = nothing
Dim myXmlTextWriter as XmlTextWriter = nothing
try
myXmlTextWriter = new XmlTextWriter (args, nothing)
myXmlTextWriter.Formatting = System.Xml.Formatting.Indented
myXmlTextWriter.WriteStartDocument(false)
myXmlTextWriter.WriteDocType("bookstore", nothing, "books.dtd", nothing)
myXmlTextWriter.WriteComment("此文件表示书店库存数据库的另一个片断")
myXmlTextWriter.WriteStartElement("bookstore")
myXmlTextWriter.WriteStartElement("book", nothing)
myXmlTextWriter.WriteAttributeString("genre","autobiography")
myXmlTextWriter.WriteAttributeString("publicationdate","1979")
myXmlTextWriter.WriteAttributeString("ISBN","0-7356-0562-9")
myXmlTextWriter.WriteElementString("title", nothing, "The Autobiography of Mark Twain")
myXmlTextWriter.WriteStartElement("Author", nothing)
myXmlTextWriter.WriteElementString("first-name", "Mark")
myXmlTextWriter.WriteElementString("last-name", "Twain")
myXmlTextWriter.WriteEndElement()
myXmlTextWriter.WriteElementString("price", "7.99")
myXmlTextWriter.WriteEndElement()
myXmlTextWriter.WriteEndElement()
'向文件写 XML 并关闭编写器
myXmlTextWriter.Flush()
myXmlTextWriter.Close()
' 读取返回的文件并进行分析以确保正确生成 XML
myXmlTextReader = new XmlTextReader (args)
FormatXml (myXmlTextReader, args)
catch e as Exception
Console.WriteLine ("异常:{0}", e.ToString())
finally
Console.WriteLine()
Console.WriteLine("对文件 {0} 的处理已完成。", args)
If Not myXmlTextReader Is Nothing
myXmlTextReader.Close()
end if
'关闭编写器
If Not myXmlTextWriter Is Nothing
myXmlTextWriter.Close()
end if
End try
End Sub
private shared Sub FormatXml (reader as XmlTextReader, filename as String)
Dim piCount, docCount, commentCount, elementCount as Integer
Dim attributeCount, textCount, whitespaceCount as Integer
While reader.Read()
Select (reader.NodeType)
case XmlNodeType.ProcessingInstruction:
Format (reader, "ProcessingInstruction")
piCount += 1
case XmlNodeType.DocumentType:
Format (reader, "DocumentType")
docCount += 1
case XmlNodeType.Comment:
Format (reader, "Comment")
commentCount += 1
case XmlNodeType.Element:
Format (reader, "Element")
elementCount += 1
While reader.MoveToNextAttribute()
Format (reader, "Attribute")
end While
if (reader.HasAttributes)
attributeCount += reader.AttributeCount
end if
case XmlNodeType.Text:
Format (reader, "Text")
textCount += 1
case XmlNodeType.Whitespace:
whitespaceCount += 1
End Select
End While
' 显示该文件的统计信息
Console.WriteLine ()
Console.WriteLine("{0} 文件的统计信息", filename)
Console.WriteLine ()
Console.WriteLine("处理指令:" piCount)
Console.WriteLine("文档类型:" docCount)
Console.WriteLine("注释:" commentCount)
Console.WriteLine("元素:" elementCount)
Console.WriteLine("属性:" attributeCount)
Console.WriteLine("文本:" textCount)
Console.WriteLine("空白:" whitespaceCount)
End Sub
private shared Sub Format(byref reader as XmlTextReader , NodeType as String)
' 格式化输出
Console.Write(reader.Depth " ")
Console.Write(reader.AttributeCount " ")
Dim i as Integer
for i = 0 to reader.Depth - 1
Console.Write(Strings.chr(9))
Next
Console.Write(reader.Prefix NodeType "" reader.Name "" reader.Value)
Console.WriteLine()
End Sub
End Class
End Namespace
参考:
有多种方法.
如果是vb.net,则其本身就有xml编辑支持,具有xml系统类,可以直接调用,再配合了listview来进行可视化处理。
如果是vb 6.0
则可以借助外部的控件,或者别人做好的控件。
其实xml也是一种可编辑的纯文本格式。
你可以在vb里用richtextbox的load方法加载,然后自己用find方法分析,在列出树形图。
DataSet 和 DataTable都有现成的方法:WriteXml
DataTable tb = this.dataGridView1.DataSource as DataTable;
if(tb != null)
{
tb.WriteXml(@"C:\table.xml",true);
return;
}
DataView dv = this.dataGridView1.DataSource as DataView;
if(dv != null)
{
dv.Table.WriteXml(@"C:\table.xml",true);
return;
}
IList list = this.dataGridView1.DataSource as IList;
if(list != null)
{
//to do,如果是IList,就要你自己想办法导出了
//XmlDocument or XmlWriter都可以考虑
}
有两种办法。
方法一、创建一个 MSXML2.DOMDocument 对象,把这个文件Load进来,按照教科书上的步骤处理。这个对象名并非唯一,依据你电脑上的MSXML版本而定。你在引用中查一下。
方法二、将这个文件当做一个普通的文本文件来处理。将它完整的读入到一个字符串中,依据节点名用Split()函数将它分段,提取所需的内容。
两种方法都不复杂,尝试一下吧。
Public Function WriteConfigInfo(ByVal aSection As String, ByVal aKey As String, _
ByVal aValue As String, ByVal aFileName As String) As Boolean
If aSection = "" Then Return False
If aFileName = "" Then Return (False)
' create in instance of the class and write the config file info
Dim XmlFile As New clsXMLCfgFile(aFileName)
Return XmlFile.WriteConfigInfo(aSection, aKey, aValue)
End Function
Public Class clsXMLCfgFile
Dim Doc As New XmlDocument()
Dim FileName As String
Dim doesExist As Boolean
Public Sub New(ByVal aFileName As String)
FileName = aFileName
Try
Doc.Load(aFileName)
doesExist = True
Catch ex As Exception
If Err.Number = 53 Then
Doc.LoadXml(("configuration" "/configuration"))
Doc.Save(aFileName)
End If
End Try
End Sub
Public Function GetConfigInfo(ByVal aSection As String, ByVal aKey As String, ByVal aDefaultValue As String) As Collection
' return immediately if the file didn't exist
If doesExist = False Then
Return New Collection()
End If
If aSection = "" Then
' if aSection = "" then get all section names
Return getchildren("")
ElseIf aKey = "" Then
' if aKey = "" then get all keynames for the section
Return getchildren(aSection)
Else
Dim col As New Collection()
col.Add(getKeyValue(aSection, aKey, aDefaultValue))
Return col
End If
End Function
Public Function WriteConfigInfo(ByVal aSection As String, ByVal aKey As String, ByVal aValue As String) As Boolean
Dim node1 As XmlNode
Dim node2 As XmlNode
If aKey = "" Then
' find the section, remove all its keys and remove the section
node1 = (Doc.DocumentElement).SelectSingleNode("/configuration/" aSection)
' if no such section, return True
If node1 Is Nothing Then Return True
' remove all its children
node1.RemoveAll()
' select its parent ("configuration")
node2 = (Doc.DocumentElement).SelectSingleNode("configuration")
' remove the section
node2.RemoveChild(node1)
ElseIf aValue = "" Then
' find the section of this key
node1 = (Doc.DocumentElement).SelectSingleNode("/configuration/" aSection)
' return if the section doesn't exist
If node1 Is Nothing Then Return True
' find the key
node2 = (Doc.DocumentElement).SelectSingleNode("/configuration/" aSection "/" aKey)
' return true if the key doesn't exist
If node2 Is Nothing Then Return True
' remove the key
If node1.RemoveChild(node2) Is Nothing Then Return False
Else
' Both the Key and the Value are filled
' Find the key
node1 = (Doc.DocumentElement).SelectSingleNode("/configuration/" aSection "/" aKey)
If node1 Is Nothing Then
' The key doesn't exist: find the section
node2 = (Doc.DocumentElement).SelectSingleNode("/configuration/" aSection)
If node2 Is Nothing Then
' Create the section first
Dim e As Xml.XmlElement = Doc.CreateElement(aSection)
' Add the new node at the end of the children of ("configuration")
node2 = Doc.DocumentElement.AppendChild(e)
' return false if failure
If node2 Is Nothing Then Return False
' now create key and value
e = Doc.CreateElement(aKey)
e.InnerText = aValue
' Return False if failure
If (node2.AppendChild(e)) Is Nothing Then Return False
Else
' Create the key and put the value
Dim e As Xml.XmlElement = Doc.CreateElement(aKey)
e.InnerText = aValue
node2.AppendChild(e)
End If
Else
' Key exists: set its Value
node1.InnerText = aValue
End If
End If
' Save the document
Doc.Save(FileName)
Return True
End Function
Private Function getKeyValue(ByVal aSection As String, ByVal aKey As String, ByVal aDefaultValue As String) As String
Dim node As XmlNode
node = (Doc.DocumentElement).SelectSingleNode("/configuration/" aSection "/" aKey)
If node Is Nothing Then Return aDefaultValue
Return node.InnerText
End Function
Private Function getchildren(ByVal aNodeName As String) As Collection
Dim col As New Collection()
Dim node As XmlNode
Try
' Select the root if the Node is empty
If aNodeName = "" Then
node = Doc.DocumentElement
Else
' Select the node given
node = Doc.DocumentElement.SelectSingleNode(aNodeName)
End If
Catch
End Try
' exit with an empty collection if nothing here
If node Is Nothing Then Return col
' exit with an empty colection if the node has no children
If node.HasChildNodes = False Then Return col
' get the nodelist of all children
Dim nodeList As XmlNodeList = node.ChildNodes
Dim i As Integer
' transform the Nodelist into an ordinary collection
For i = 0 To nodeList.Count - 1
col.Add(nodeList.Item(i).Name)
Next
Return col
End Function
End Class
Top
把它放模块中,稍微调试一下:)就OK了