在.NET中操作XmlDocument,XmlReader的方法

用XmlDocument进行读取

大家想必一定都了解XML,利用XML技术来存储数据和文档是一件很容易的事情,.NET Framework 在它的命名空间System.Xml 就提供了一种可以很方便的操作xml的类XmlDocument,它使用起来非常容易,XmlDocument 其实就是一个简单的树。下面详细的介绍XmlDocument 的使用方法。

    下面是这个类中操作节点的常用方法。

// create a new node in the document object from the source node
    //and name it as "sName"
// the return value indicates success or failure
public bool AddNode(XmlNode oSource, String sName);

// same as above except that it also specifies the parent node of the
    // newly created node
// the return value indicates success or failure (returns false if the
    // parent node does not exist)
public bool AddNode(XmlNode oSource, String sName, String sParent);

// create a set of new nodes in the document object from the source node
    // list and name them as "sName"
// the return value indicates success or failure
public bool AddNodes(XmlNodeList oSourceList, String sName);

// same as above except that it also specifies the parent node of the
    // newly created nodes the return value indicates success or failure
    // (returns false if the parent node
    // does not exist)
public bool AddNodes(XmlNodeList oSourceList, String sName, String sParent);

// merge the source node into a node named "sName" in the document object
// the node named "sName" will be created if it does not exist
// the return value indicates success or failure
public bool MergeNode(XmlNode oSource, String sName);

// same as above except that it also specifies the parent node of the merged node
// the return value indicates success or failure (returns false if the parent node
    // does not exist)
public bool MergeNode(XmlNode oSource, String sName, String sParent);

下面我们给一个增加节点的例子

docVechile.xml

<VehicleData>
    <Record>
        <id>1001</id>
        <make>Ford</make>
        <model>Escort</model>
        <year>1984</year>
    </Record>
    <Record>
        <id>1002</id>
        <make>Toyota</make>
        <model>Tercel</model>
        <year>1996</year>
    </Record>
    <Record>
        <id>1003</id>
        <make>Mazda</make>
        <model>GLC</model>
        <year>1985</year>
    </Record>
</VehicleData>
docDriver.xml

<DriverData>
    <Record>
        <id>1</id>
        <firstname>Albert</firstname>
        <lastname>Einstein</lastname>
    </Record>
    <Record>
        <id>2</id>
        <firstname>Clint</firstname>
        <lastname>Eastwood</lastname>
    </Record>
    <Record>
        <id>3</id>
        <firstname>James</firstname>
        <lastname>Bond</lastname>
    </Record>
</DriverData>

下面的代码将增加一个节点:

Dim myDoc As XMLDocumentEx = New XMLDocumentEx()
myDoc.LoadXml("<Data></Data>")
myDoc.AddNode(docVehicle.SelectSingleNode("//Record"), "VehicleRecord", "Data")
myDoc.AddNode(docDriver.SelectSingleNode("//Record"), "DriverRecord", "Data")
myDoc.xml<Data>
    <VehicleRecord>
         <id>...</id>
        <make>...</make>
        <model>...</model>
        <year>...</year>
    </ Vehicle Record>
    <DriverRecord>
        <id>...</id>
        <firstname>...</firstname>
        <lastname>...</lastname>
    </DriverRecord>
   
</Data> 我们也可是使用AddNodes方法把一个记录集的所有记录增加到节点上:Dim myDoc As XMLDocumentEx = New XMLDocumentEx()
myDoc.LoadXml("<Data> <VehicleData></Vehicle Data><DriverData></DriverData> </Data>")
myDoc.AddNodes(docVehicle.SelectNodes("//Record"), "VehicleRecord", " Vehicle Data")
myDoc.AddNodes(docDriver.SelectNodes("//Record"), "DriverRecord", "DriverData")结果如下:myDoc.xml<Data>
     <VehicleData>
        <VehicleRecord>
            <id>1001</id>
            <make>Ford</make>
            <model>Escort</model>
            <year>1984</year>
        </VehicleRecord>
        <VehicleRecord>
            <id>1002</id>
            <make>Toyota</make>
            <model>Tercel</model>
            <year>1996</year>
        </VehicleRecord>
        <VehicleRecord>
            <id>1003</id>
            <make>Mazda</make>
            <model>GLC</model>
            <year>1985</year>
        </VehicleRecord>
    </VehicleData>
     <DriverData>
        <DriverRecord>
            <id>1</id>
            <firstname>Albert</firstname>
            <lastname>Einstein</lastname>
        </DriverRecord>
        <DriverRecord>
            <id>2</id>
            <firstname>Clint</firstname>
            <lastname>Eastwood</lastname>
        </DriverRecord>
        <DriverRecord>
            <id>3</id>
            <firstname>James</firstname>
            <lastname>Bond</lastname>
        </DriverRecord>
    </DriverData>
   
</Data>下面我介绍如何合并节点。假设我们有两个XmlDocument文件docBook1和docBook2,这两个文档都包含 <Book> 节点.  在docBook1 中的这个 <Book> 节点 包含 <Introduction>, <Chapter1>, and <Chapter2>.  在docBook2中的这个 <Book> 节点 包含 <Chapter3>, <Chapter4>, and <Chapter5>.  下面的代码演示如何合并这两个book节点:Dim myDoc As XMLDocumentEx = New XMLDocumentEx()
myDoc.LoadXml("<Data> <Book></Book></Data> ")
myDoc.MergeNode(docBook1.SelectSingleNode("//Book"), "Book", "Data ")
myDoc.MergeNode(docBook2.SelectSingleNode("//Book"), "Book", "Data")合并后的效果如下:myDoc.xml<Data>
    <Book>
        <Introduction>...</Introduction>
        < Chapter1 >...</Chapter1>
        <Chapter2>...</Chapter2>
        <Chapter3>...</Chapter3>
        <Chapter4>...</Chapter4>
        <Chapter5>...</Chapter5>
    </Book>
</Data>下面是所有的源代码:sealed public class XMLDocumentEx: XmlDocument
{
    public bool AddNode(XmlNode oSource, String sName)
    {
        return AddNode(oSource, sName, null);
    }
    public bool AddNode(XmlNode oSource, String sName, String sParent)
    {
        try
        {
            if(sName!=null&&oSource!= null)
            {
                // create the new node with given name
                XmlNode oNewNode = CreateElement(sName);
                // copy the contents from the source node
                oNewNode.InnerXml = oSource.InnerXml;
                // if there is no parent node specified, then add
                // the new node as a child node of the root node
                if(sParent!= null) sParent = sParent.Trim();
                if(sParent== null||sParent.Equals(String.Empty))
                {
                    DocumentElement.AppendChild(oNewNode);
                    return true;
                }
                // otherwise add the new node as a child of the parent node
                else
                {
                    if (!sParent.Substring(0,2).Equals("//")) sParent = "//"+sParent;
                    XmlNode oParent = SelectSingleNode(sParent);
                    if (oParent!=null)
                    {
                        oParent.AppendChild(oNewNode);
                        return true ;
                    }
                }
            }
        }
        catch (Exception)
        {
            // error handling code
        }
        return false;
    }
    public bool AddNodes(XmlNodeList oSourceList, String sName)
    {
        return AddNodes(oSourceList, sName, null);
    }
    public bool AddNodes(XmlNodeList oSourceList, String sName, String sParent)
    {
        try
        {
            if(oSourceList!= null)
            {
                // call AddNode for each item in the source node list
                // return true only if all nodes are added successfully
                int i = 0;
                while(i<oSourceList.Count)
                {
                    if (!AddNode(oSourceList.Item(i),sName,sParent)) return false;
                    i++;
                }
                return true;
            }
        }
        catch (Exception)
        {
            // error handling code
        }
        return false;
    }
    public bool MergeNode(XmlNode oSource, String sName)
    {
        return MergeNode(oSource, sName, null );
    }
    public bool MergeNode(XmlNode oSource, String sName, String sParent)
    {
        try
        {
            if(sName!=null&&oSource!= null)
            {
                XmlNode theNode = null ;
                // if there is no parent node specified ...
                if(sParent!= null) sParent = sParent.Trim();
                if(sParent== null||sParent.Equals(String.Empty))
                {
                    // if the node with specified name does not exist,
                    // add it as a child node of the root node
                    theNode = SelectSingleNode("//"+sName);
                    if (theNode==null)
                    {
                        theNode = CreateElement(sName);
                        DocumentElement.AppendChild(theNode);
                    }
                }
                // if the parent node is specified ...
                else
                {
                    // find the parent node
                    if (!sParent.Substring(0,2).Equals("//")) sParent = "//"+sParent;
                    XmlNode theParent = SelectSingleNode(sParent);
                    if (theParent!=null)
                    {
                        // if the node with specified name does not exist, create
                        // it first, then add it as a child node of the parent node
                        theNode = theParent.SelectSingleNode(sName);
                        if(theNode==null)
                        {
                            theNode = CreateElement(sName);
                            theParent.AppendChild(theNode);
                        }
                    }
                }
                // merge the content of the source node into
                // the node with specified name
                if(theNode!= null)
                {
                    theNode.InnerXml += oSource.InnerXml;
                    return true;
                }
            }
        }
        catch (Exception)
        {
        }
        return false;
    }
}

 

用XmlReader进行读取的方法

摘要
组成.NET平台的关键技术之一就是XML,这里简单谈谈如何使用.NET中的XmlReader。

1. XMLReader简介
XmlReader是一种快速、无缓冲、向前并只读的游标,用于读取XML文档,并且隐藏了底层数据交换的复杂性。XmlReader作为一种"拉模型"较"推模型"的SAX有了多种优势,最主要的一个就是它更易使用,其次性能更为提高、并减少了编程的难度。
XmlReader类是一个抽象类,XmlTextReader,XmlValidatingReader,和XmlNodeReader类都继承自XmlReader类。XmlReader类有很多方法和属性用来读取XML文件的内容、查找XML元素的深度、判断当前元素的内容是否为空,以及导航XML的属性等。

2. XMLReader应用
在.NET构架中,XML类均被定义在System.Xml名称空间中,如:XmlReader、XmlTextReader、 XmlValidatingReader、XmlNodeReader、XmlWriter、和XmlTextWriter,因此使用XmlReader时应该引入System.Xml。

下面是一个简单的读取XML的控制台程序。
[Visual Basic]
Imports System
Imports System.Xml

Module Module1
Sub Main(ByVal CmdArgs() As String)
Try
Dim sFileName As String = CmdArgs(0)
Dim xtr As New XmlTextReader(sFileName)

xtr.Read()

Console.WriteLine("<{0}>", xtr.Name)
Console.WriteLine(xtr.ReadInnerXml())
Console.WriteLine("</{0}>", xtr.Name)
xtr.Close()
Catch eErr As Exception
Console.WriteLine("Error:/t{0}", eErr.Message)
End Try
End Sub
End Module

[C#]
using System;
using System.Xml;

namespace ConsoleApplicationXmlReader
{
class ClassXmlReader
{
static void Main(string[] args)
{
try
{
String sFileName = args[0];
XmlTextReader xtr = new XmlTextReader(sFileName);
xtr.Read();
Console.WriteLine("<{0}>", xtr.Name);
Console.WriteLine(xtr.ReadInnerXml());
Console.WriteLine("</{0}>", xtr.Name);
xtr.Close();
}
catch (Exception e)
{
Console.WriteLine("Error:/t{0}", e.Message);
}
return;
}
}
}

测试使用的XML文件,People.xml
<People>
<Person>
<Name>
<FirstName>Joe</FirstName>
<LastName>Suits</LastName>
</Name>
<Address>
<Street>1800 Success Way</Street>
<City>Redmond</City>
<State>WA</State>
<ZipCode>98052</ZipCode>
</Address>
<Job>
<Title>CEO</Title>
<Description>Wears the nice suit</Description>
</Job>
</Person>

<Person>
<Name>
<FirstName>Linda</FirstName>
<LastName>Sue</LastName>
</Name>
<Address>
<Street>1302 American St.</Street>
<City>Paso Robles</City>
<State>CA</State>
<ZipCode>93447</ZipCode>
</Address>
<Job>
<Title>Attorney</Title>
<Description>Stands up for justice</Description>
</Job>
</Person>
</People>

可以通过调用命令提示符运行程序,如:E:/>ConsoleApplication_XmlReader.exe people.xml

3. 小结
.NET的XmlReader提供了一种访问XML数据的良好接口,让开发人员更为轻松的读取XML文件中的内容,使得快速应用.NET成为可能。

根据MSDN帮助文档:用XmlDocument进行读取时由于是将整个文件读入缓存中,并且文件的大小要小于1M;而用XmlReader来读取的话是不需要读入缓存的,并且读取的时候是只读往前的,效率较高

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值