C#操作XML文件

来源:互联网 发布:复旦大学网络教育专业 编辑:程序博客网 时间:2024/06/05 13:32

使用 System.XML

·        using System.Xml;
//
初始化一个xml实例
XmlDocument xml=new XmlDocument();

//导入指定xml文件
xml.Load(path);
xml.Load(HttpContext.Current.Server.MapPath("~/file/bookstore.xml"));

//指定一个节点
XmlNode root=xml.SelectSingleNode("/root");

//获取节点下所有直接子节点
XmlNodeList childlist=root.ChildNodes;

//判断该节点下是否有子节点
root.HasChildNodes;

//获取同名同级节点集合
XmlNodeList nodelist=xml.SelectNodes("/Root/News");

//生成一个新节点
XmlElement node=xml.CreateElement("News");

//将节点加到指定节点下,作为其子节点
root.AppendChild(node);

//将节点加到指定节点下某个子节点前
root.InsertBefore(node,root.ChildeNodes[i]);

//为指定节点的新建属性并赋值
node.SetAttribute("id","11111");

//为指定节点添加子节点
root.AppendChild(node);

//获取指定节点的指定属性值
string id=node.Attributes["id"].Value;

//获取指定节点中的文本
string content=node.InnerText;

//保存XML文件
string path=Server.MapPath("~/file/bookstore.xml");
xml.Save(path);
//or use :xml.Save(HttpContext.Current.Server.MapPath("~/file/bookstore.xml"));


二、具体实例


C#.net中如何操作XML
需要添加的命名空间:
using System.Xml;

定义几个公共对象:
XmlDocument xmldoc ;
XmlNode xmlnode ;
XmlElement xmlelem ;

1,创建到服务器同名目录下的xml文件:


方法一:
xmldoc = new XmlDocument ( ) ;
//
加入XML的声明段落,<?xmlversion="1.0" encoding="gb2312"?>
XmlDeclaration xmldecl;
xmldecl = xmldoc.CreateXmlDeclaration("1.0","gb2312",null);
xmldoc.AppendChild ( xmldecl);

//加入一个根元素
xmlelem = xmldoc.CreateElement ( "" , "Employees" ,"" ) ;
xmldoc.AppendChild ( xmlelem ) ;
//
加入另外一个元素
for(int i=1;i<3;i++)
{

XmlNode root=xmldoc.SelectSingleNode("Employees");//查找<Employees>
XmlElement xe1=xmldoc.CreateElement("Node");//
创建一个<Node>节点
xe1.SetAttribute("genre","
李赞红");//设置该节点genre属性
xe1.SetAttribute("ISBN","2-3631-4");//
设置该节点ISBN属性

XmlElement xesub1=xmldoc.CreateElement("title");
xesub1.InnerText="CS
从入门到精通";//设置文本节点
xe1.AppendChild(xesub1);//
添加到<Node>节点中
XmlElement xesub2=xmldoc.CreateElement("author");
xesub2.InnerText="
候捷";
xe1.AppendChild(xesub2);
XmlElement xesub3=xmldoc.CreateElement("price");
xesub3.InnerText="58.3";
xe1.AppendChild(xesub3);

root.AppendChild(xe1);//添加到<Employees>节点中
}
//
保存创建好的XML文档
xmldoc.Save ( Server.MapPath("data.xml") ) ;

//////////////////////////////////////////////////////////////////////////////////////
结果:在同名目录下生成了名为data.xml的文件,内容如下,
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="
李赞红" ISBN="2-3631-4">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
<Node genre="
李赞红" ISBN="2-3631-4">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
</Employees>


方法二:
XmlTextWriter xmlWriter;
   string strFilename = Server.MapPath("data1.xml") ;

   xmlWriter = newXmlTextWriter(strFilename,Encoding.Default);//创建一个xml文档
   xmlWriter.Formatting = Formatting.Indented;
   xmlWriter.WriteStartDocument();
   xmlWriter.WriteStartElement("Employees");

   xmlWriter.WriteStartElement("Node");
   xmlWriter.WriteAttributeString("genre","
李赞红");
  xmlWriter.WriteAttributeString("ISBN","2-3631-4");

   xmlWriter.WriteStartElement("title");
   xmlWriter.WriteString("CS
从入门到精通");
   xmlWriter.WriteEndElement();

   xmlWriter.WriteStartElement("author");
   xmlWriter.WriteString("
候捷");
   xmlWriter.WriteEndElement();

   xmlWriter.WriteStartElement("price");
   xmlWriter.WriteString("58.3");
   xmlWriter.WriteEndElement();

   xmlWriter.WriteEndElement();

   xmlWriter.Close();
//////////////////////////////////////////////////////////////////////////////////////
结果:
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="
李赞红" ISBN="2-3631-4">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
</Employees>

2,添加一个结点:

XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load(Server.MapPath("data.xml"));
XmlNode root=xmlDoc.SelectSingleNode("Employees");//
查找<Employees>
XmlElement xe1=xmlDoc.CreateElement("Node");//
创建一个<Node>节点
xe1.SetAttribute("genre","
张三");//设置该节点genre属性
xe1.SetAttribute("ISBN","1-1111-1");//
设置该节点ISBN属性

XmlElement xesub1=xmlDoc.CreateElement("title");
xesub1.InnerText="C#
入门帮助";//设置文本节点
xe1.AppendChild(xesub1);//
添加到<Node>节点中
XmlElement xesub2=xmlDoc.CreateElement("author");
xesub2.InnerText="
高手";
xe1.AppendChild(xesub2);
XmlElement xesub3=xmlDoc.CreateElement("price");
xesub3.InnerText="158.3";
xe1.AppendChild(xesub3);

root.AppendChild(xe1);//添加到<Employees>节点中
xmlDoc.Save ( Server.MapPath("data.xml") );

//////////////////////////////////////////////////////////////////////////////////////
结果:在xml原有的内容里添加了一个结点,内容如下,
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="
李赞红" ISBN="2-3631-4">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
<Node genre="
李赞红" ISBN="2-3631-4">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
<Node genre="
张三" ISBN="1-1111-1">
    <title>C#
入门帮助</title>
    <author>
高手</author>
    <price>158.3</price>
</Node>
</Employees>

3,修改结点的值(属性和子结点):

XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load( Server.MapPath("data.xml") );

XmlNodeList nodeList=xmlDoc.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点

foreach(XmlNode xn in nodeList)//遍历所有子节点
{
XmlElement xe=(XmlElement)xn;//
将子节点类型转换为XmlElement类型
if(xe.GetAttribute("genre")=="
张三")//如果genre属性值为张三
{
xe.SetAttribute("genre","update
张三");//则修改该属性为“update张三

XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
foreach(XmlNode xn1 in nls)//
遍历
{
XmlElement xe2=(XmlElement)xn1;//
转换类型
if(xe2.Name=="author")//
如果找到
{
xe2.InnerText="
亚胜";//则修改
}
}
}
}
xmlDoc.Save( Server.MapPath("data.xml") );//
保存。

//////////////////////////////////////////////////////////////////////////////////////
结果:将原来的所有结点的信息都修改了,xml的内容如下,
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="
李赞红" ISBN="2-3631-4">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
<Node genre="
李赞红" ISBN="2-3631-4">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
<Node genre="update
张三" ISBN="1-1111-1">
    <title>C#
入门帮助</title>
    <author>
亚胜</author>
    <price>158.3</price>
</Node>
</Employees>

4,修改结点(添加结点的属性和添加结点的自结点):
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load( Server.MapPath("data.xml") );

XmlNodeListnodeList=xmlDoc.SelectSingleNode("Employees").ChildNodes;//获取Employees节点的所有子节点

foreach(XmlNode xn in nodeList)
{
XmlElement xe=(XmlElement)xn;
xe.SetAttribute("test","111111");

XmlElement xesub=xmlDoc.CreateElement("flag");
xesub.InnerText="1";
xe.AppendChild(xesub);
}
xmlDoc.Save( Server.MapPath("data.xml") );

//////////////////////////////////////////////////////////////////////////////////////
结果:每个结点的属性都添加了一个,子结点也添加了一个,内容如下,
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="
李赞红" ISBN="2-3631-4" test="111111">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
    <flag>1</flag>
</Node>
<Node genre="
李赞红" ISBN="2-3631-4" test="111111">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
    <flag>1</flag>
</Node>
<Node genre="update
张三" ISBN="1-1111-1" test="111111">
    <title>C#
入门帮助</title>
    <author>
亚胜</author>
    <price>158.3</price>
    <flag>1</flag>
</Node>
</Employees>

5,删除结点中的某一个属性:
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load( Server.MapPath("data.xml") );
XmlNodeList xnl=xmlDoc.SelectSingleNode("Employees").ChildNodes;
foreach(XmlNode xn in xnl)
{
XmlElement xe=(XmlElement)xn;
xe.RemoveAttribute("genre");//
删除genre属性

XmlNodeList nls=xe.ChildNodes;//继续获取xe子节点的所有子节点
foreach(XmlNode xn1 in nls)//
遍历
{
XmlElement xe2=(XmlElement)xn1;//
转换类型
if(xe2.Name=="flag")//
如果找到
{
xe.RemoveChild(xe2);//
则删除
}
}
}
xmlDoc.Save( Server.MapPath("data.xml") );

//////////////////////////////////////////////////////////////////////////////////////]
结果:删除了结点的一个属性和结点的一个子结点,内容如下,
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node ISBN="2-3631-4" test="111111">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
<Node ISBN="2-3631-4" test="111111">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
<Node ISBN="1-1111-1" test="111111">
    <title>C#
入门帮助</title>
    <author>
亚胜</author>
    <price>158.3</price>
</Node>
</Employees>

6,删除结点:
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load( Server.MapPath("data.xml") );
XmlNode root=xmlDoc.SelectSingleNode("Employees");
XmlNodeList xnl=xmlDoc.SelectSingleNode("Employees").ChildNodes;
for(int i=0;i<xnl.Count;i++)
{
XmlElement xe=(XmlElement)xnl.Item(i);
if(xe.GetAttribute("genre")=="
张三")
{
root.RemoveChild(xe);
if(i<xnl.Count)i=i-1;
}
}
xmlDoc.Save( Server.MapPath("data.xml") );

//////////////////////////////////////////////////////////////////////////////////////]
结果:删除了符合条件的所有结点,原来的内容:

<?xml version="1.0"encoding="gb2312"?>
<Employees>
<Node genre="
李赞红" ISBN="2-3631-4">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
<Node genre="
李赞红" ISBN="2-3631-4">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
<Node genre="
张三" ISBN="1-1111-1">
    <title>C#
入门帮助</title>
    <author>
高手</author>
    <price>158.3</price>
</Node>
<Node genre="
张三" ISBN="1-1111-1">
    <title>C#
入门帮助</title>
    <author>
高手</author>
    <price>158.3</price>
</Node>
</Employees>

删除后的内容:
<?xml version="1.0" encoding="gb2312"?>
<Employees>
<Node genre="
李赞红" ISBN="2-3631-4">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
<Node genre="
李赞红" ISBN="2-3631-4">
    <title>CS
从入门到精通</title>
    <author>
候捷</author>
    <price>58.3</price>
</Node>
</Employees>

7,按照文本文件读取xml

System.IO.StreamReader myFile =new
System.IO.StreamReader(Server.MapPath("data.xml"),System.Text.Encoding.Default);
//
注意System.Text.Encoding.Default

string myString = myFile.ReadToEnd();//myString是读出的字符串
myFile.Close();

三、高级应用

/*读取xml数据  两种xml方式*/
<aaa>
     <bb>something</bb>
     <cc>something</cc>
</aaa>

<aaa>
    <add key="123" value="321"/>
</aaa>

/*第一种方法*/
DS.ReadXml("your xmlfile name");
Container.DataItem("bb");
Container.DataItem("cc");
DS.ReadXmlSchema("your xmlfile name");

/*
第二种方法*/
<aaa>
    <add key="123" value="321"/>
</aaa>
如果我要找到123然后取到321应该怎么写呢?

using System.XML;
XmlDataDocument xmlDoc = new System.Xml.XmlDataDocument();
xmlDoc.Load(@"c:Config.xml");
XmlElement elem = xmlDoc.GetElementById("add");
string str = elem.Attributes["value"].Value


/*
第三种方法:SelectSingleNode读取两种格式的xml *---/
--------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
       <ConnectionString>Data Source=yf;user id=ctm_dbo;password=123</ConnectionString>            
</appSettings>
</configuration>
--------------------------------------------------------------------------
XmlDocument doc = new XmlDocument();
doc.Load(strXmlName);

    XmlNode node=doc.SelectSingleNode("/configuration/appSettings/ConnectionString");
    if(node!=null)
    {
     string k1=node.Value;    //null
     string k2=node.InnerText;//Data Source=yf; userid=ctm_dbo;password=123
     string k3=node.InnerXml;//Data Source=yf; userid=ctm_dbo;password=123
     node=null;
    }

********************************************************************
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
       <add key="ConnectionString"value="Data Source=yf; user id=ctm_dbo;password=123"/>            
</appSettings>
</configuration>
**--------------------------------------------------------------------**
     XmlNodenode=doc.SelectSingleNode("/configuration/appSettings/add");
    if(node!=null)
    {
     string k=node.Attributes["key"].Value;
     string v=node.Attributes["value"].Value;
     node=null;
    }
*--------------------------------------------------------------------*
    XmlNodenode=doc.SelectSingleNode("/configuration/appSettings/add");
    if(node!=null)
    {
     XmlNodeReader nr=new XmlNodeReader(node);
     nr.MoveToContent();
    //
检查当前节点是否是内容节点。如果此节点不是内容节点,则读取器向前跳至下一个内容节点或文件结尾。
     nr.MoveToAttribute("value");
     string s=nr.Value;
     node=null;
    }

·        要对XML文件进行操作,须要声明以下命名空间:
using System.Xml;

一、检查指定XML文件是否存在

            System.IO.File.Exists(文件路径及名称);

二、利用C#编程创建 XML文件

        我在网上找到了这样的两段代码:
        
代码一:
            XmlDocument xmldoc = new XmlDocument();
            XmlNode xmlnode;
            XmlElement xmlelem;
            XmlElement xmlelem2;
             XmlTextxmltext;

            //加入XML的声明段落
            xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "","");
            xmlnode.InnerText+=" encoding=\"GB2312\"";
            xmldoc.AppendChild(xmlnode);

            //加入一个根元素
             xmlelem= xmldoc.CreateElement("", "ROOT", "");
            xmltext = xmldoc.CreateTextNode("Root Text");
            xmlelem.AppendChild(xmltext);
            xmldoc.AppendChild(xmlelem);

            //加入另外一个元素
            xmlelem2 = xmldoc.CreateElement("SampleElement");
            xmlelem2 =xmldoc.CreateElement("","SampleElement","");
            xmltext = xmldoc.CreateTextNode("The text of the sample element");
            xmlelem2.AppendChild(xmltext);
            xmldoc.ChildNodes.Item(1).AppendChild(xmlelem2);

            //保存创建好的XML文档
             try
             {
                xmldoc.Save("data.xml");
             }
             catch(Exception f)
             {
                //
显示错误信息
                MessageBox.Show(f.Message);
             }
            //Console.ReadLine();
        
这段代码在win2003ser+vs2005环境下测试成功,但是XML文件格式很乱,我不知道怎样调整格式,知道的朋友请赐教。

        代码二:
             stringFileName =Application.StartupPath+"\\phone.xml";
            XmlTextWriter objXmlTextWriter = new XmlTextWriter(FileName,Encoding.Default);

            objXmlTextWriter.Formatting = Formatting.Indented;
            objXmlTextWriter.Indentation = 6;

            objXmlTextWriter.WriteStartDocument();

            objXmlTextWriter.WriteStartElement("", "PhoneBook","");

            objXmlTextWriter.WriteStartElement("", "Name","");
            objXmlTextWriter.WriteString("
加菲尔德
");
            objXmlTextWriter.WriteEndElement();

            objXmlTextWriter.WriteStartElement("", "Number","");
            objXmlTextWriter.WriteString("5555555");
            objXmlTextWriter.WriteEndElement();

            objXmlTextWriter.WriteStartElement("", "City","");
            objXmlTextWriter.WriteString("
纽约
");
            objXmlTextWriter.WriteEndElement();

            objXmlTextWriter.WriteStartElement("", "DateOfBirth","");
            objXmlTextWriter.WriteString("26/10/1978");
            objXmlTextWriter.WriteEndElement();

            objXmlTextWriter.WriteEndElement();
            objXmlTextWriter.WriteEndDocument();

            objXmlTextWriter.Flush();

            objXmlTextWriter.Close();
        
这段代码在win2003ser+vs2005环境下测试通过,出来的效果很好,也比较容易理解,我一般就是用这段代码创建XML文件。

三、读取、修改XML文件的某个节点的值

            string path = "phone.xml";  
             XmlDocumentdoc = new XmlDocument();
            doc.Load(path);
             //
读所有节点表

            XmlNamespaceManager xnm = new XmlNamespaceManager(doc.NameTable);
             //
读取节点值
            XmlNode node = doc.SelectSingleNode("/PhoneBook/Name", xnm);  //node.InnerText
就是读取出来的值

            //修改节点值
            node.InnerText="
要修改的内容";

            //保存修改后的内容
            doc.Save(path);

·                    引用命名空间:using System.Xml 

1.检查所要操作的xml文件是否存在:

   System.IO.File.Exists(文件路径及名称);

2.得到xml文件:

1)在asp.net中可以这样得到:

XmlDocument xmlDoc = newXmlDocument();

//导入xml文档

xmlDoc.Load(Server.MapPath("xmlTesting.xml"));

//导入字符串

//xmlDoc.LoadXml("<bookStore> <book id="01" price="3.5">读者</book></bookStore>");

注:Server.MapPath("xmlTesting.xml")此时的xmlTesting.xml文件必须是在当前的解决方案里;同样可以写成完整的物理路径xmlDoc.Load (@"E:"软件学习"测试"myNoteWeb"xmlTesting.xml")

2)在windForm直接用物理路径得到所要操作的xml文件具体实现方法同上

3.创建xml文件:

 XmlDocument xmlDoc =new XmlDocument(); //创建xml文档(实例化一个xml)

XmlNode root =xmlDoc.CreateElement("bookStore");//创建根节点

//创建第1个子结点:

XmlNode bookNode =xmlDoc.CreateElement("book");

bookNode.InnerText ="读者";

//为此节点添加属性

 1

 bookPublishNode.SetAttribute("id","01")

 root.AppendChild(bookNode);

2

 XmlAttributexmlattribute = tempXmlDoc.CreateAttribute("price");

 xmlattribute.Value ="3.5";

 tempRoot .Attributes.Append (xmlattribute )

 //创建第2个根节点的子结点:

 XmlNode tempBookNode= xmlDoc.CreateElement("tempbook ");

 tempBookNode.InnerText="文摘";

 root.AppendChild(tempBookNode);

·        方法一:使用XML控件

 

<%@ Page Language="C#"%>   
<html>   
<body>   
<h3><font face="Verdana">
读取XML方法一
</font></h3>   
<from runat=server>   
<asp:Xml id="xml1" DocumentSource="grade.xml"runat="server" />   
</from>   
 
</body>   
</html> 


方法二:使用DOM技术

 

<%@ Page Language="C#"%>   
<% @ Import Namespace="System.Xml"%>   
<% @ Import Namespace="System.Xml.Xsl"%>   
<html>   
<script language="C#"runat="server">   
void Page_Load(Object sender,EventArgs e)   
{   
XmlDocument doc=new XmlDocument();   
doc.Load(Server.MapPath("grade.xml"));   
xml1.Document=doc;   
}   
</script>   
<body>   
<h3><font face="Verdana">
读取XML方法二
</font></h3>   
<from runat=server>   
<asp:Xml id="xml1" runat="server"/>   
</from>   
 
</body>   
</html> 


方法三:使用DataSet对象

 

<%@ Page Language="C#"%>   
<% @ Import Namespace="System.Data"%>   
<% @ Import Namespace="System.Data.OleDb"%>   
<script language="C#"runat="server">   
void Page_Load(Object sender,EventArgs e)   
{   
DataSet objDataSet=new DataSet();   
objDataSet.ReadXml(Server.MapPath("grade.xml"));   
dgEmployees.DataSource=objDataSet.Tables["student"].DefaultView;   
dgEmployees.DataBind();   
}   
</script>   
<body>   
<h3><font face="Verdana">
读取XML方法三
</font></h3>   
<asp:DataGrid id="dgEmployees" runat="server"/>   
 
</body>   
</html> 


方法四:按文本方式读取

 

<%@ Page Language="C#"%>   
<% @ Import Namespace="System.Xml"%>   
<html>   
<script language="C#"runat="server">   
private void Page_Load(Object sender,EventArgs e)   
{   
XmlTextReader objXMLReader=new XmlTextReader(Server.MapPath("grade.xml"));   
string strNodeResult="";   
XmlNodeType objNodeType;   
while(objXMLReader.Read())   
{   
objNodeType =objXMLReader.NodeType;   
swith(objNodeType)   
{   
case XmlNodeType.XmlDeclaration:   
//
读取XML文件头
   
strNodeResult+="XML Declaration:<b>"+objXMLReader.Name+""+objXMLReader.Value+"</b><br/>";   
break;   
case XmlNodeType.Element:   
//
读取标签
   
strNodeResult+="Element:<b>"+objXMLReader.Name+"</b><br/>";   
break;   
case XmlNodeType.Text:   
//
读取值
   
strNodeResult+="&nbsp;-Value:<b>"+objXMLReader.Value+"</b><br/>";   
break;   
 
}   
//
判断该节点是否有属性
   
if(objXMLReader.AttributeCount>0)   
{ //
用循环判断完所有节点
   
while(objXMLReader.MoveToNextAttibute)   
{ //
取标签和值
   
strNodeResult+="&nbsp;-Attribute:<b>"+objXMLReader.Name+"</b>&nbsp;value:<b>"+objXMLReader.Value+"</b><br/>";   
}   
}   
LblFile.Text=strNodeResult;   
}   
}   
</script>   
<body>   
<h3><font face="Verdana">
读取XML方法四
</font></h3>   
<from runat=server>   
<asp:label id="LblFile" runat="server" />   
</from>   
 
</body>   
</html> 

 

 

 

 

 

·        ASP.NET中常用功能代码总结(XML文件操作篇)
一.写入XML文件 

 1/**//// <summary>
 2/// 写入XML文件
 3/// </summary>
 4private void WriteXML()
 5{
 6    /**//// 创建一个表示所要生成的XML文件路径的字符串。如果该路径指向NTFS分区,则需要相关的访问权限。
 7    string filename = XMLFilePathTextBox.Text;
 8    
 9    /**//// 创建一个写入XML数据的文件流
10    System.IO.FileStream myFileStream = new System.IO.FileStream(filename, System.IO.FileMode.Create);
11    
12    /**//// 使用文件流对象创建一个XmlTextWriter对象
13    XmlTextWriter myXmlWriter = new XmlTextWriter(myFileStream, System.Text.Encoding.Unicode);
14
15    myXmlWriter.Formatting = Formatting.Indented;
16
17    try
18    {
19        /**//// 使用WriteXMLbyXmlWriter方法把数据写入XmlTextWriter对象中
20        WriteXMLbyXmlWriter(myXmlWriter, "MSFT", 74.5, 5.5, 49020000);
21        
22        /**//// 通过Close方法的调用,XmlTextWriter对象的数据最终写入XML文件
23        myXmlWriter.Close();
24        Page.Response.Write("生成XML文档成功!");
25    }
26    catch
27    {
28        Page.Response.Write("生成XML文档失败!请检查路径是否正确,以及是否有写入权限。");
29    }
30}
31
32private void WriteXMLbyXmlWriter(XmlWriter writer, string symbol, double price, double change, long volume)
33{
34    writer.WriteStartElement("Stock");
35    writer.WriteAttributeString("Symbol", symbol);
36    writer.WriteElementString("Price", XmlConvert.ToString(price));
37    writer.WriteElementString("Change", XmlConvert.ToString(change));
38    writer.WriteElementString("Volume", XmlConvert.ToString(volume));
39    writer.WriteEndElement();
40} 

 二.通过DOM读取XML文件 

 1/**//// <summary>
 2/// 通过DOM读取XML文件
 3/// </summary>
 4private void ReadXMLbyDOM()
 5{
 6    /**//// 创建XmlDocument类的实例
 7    XmlDocument doc = new XmlDocument();
 8    ArrayList NodeValues = new ArrayList();
 9    
10    /**//// people.xml文件读入内存,形成一个DOM结构
11    doc.Load( Server.MapPath("people.xml") );
12    XmlNode root = doc.DocumentElement;
13    foreach( XmlNode personElement in root.ChildNodes )
14        NodeValues.Add(personElement.FirstChild.Value);
15
16    XMLNodeListBox.DataSource = NodeValues;
17    XMLNodeListBox.DataBind();
18}
19 

 三.通过XMLReader读取XML文件 

 1/**//// <summary>
 2/// 通过XMLReader读取XML文件
 3/// </summary>
 4private void ReadXMLbyXmlReader()
 5{
 6    /**////创建XML读取器
 7    XmlTextReader reader = new XmlTextReader( Server.MapPath("students.xml") );
 8    ArrayList NodeValues = new ArrayList();
 9
10    while( reader.Read() ) 
11    {
12        if( reader.NodeType == XmlNodeType.Element && reader.Name == "NAME" )
13        {
14            reader.Read();
15            NodeValues.Add( reader.Value );
16        }
17    }
18
19    XMLNodeListBox.DataSource = NodeValues;
20    XMLNodeListBox.DataBind();
21} 

 四.通过Xpath读取XML文件 

 1/**//// <summary>
 2/// 通过Xpath读取XML文件
 3/// </summary>
 4private void ReadXMLbyXpath()
 5{    
 6    /**////注意:需要引入System.XML.XPath命名空间
 7    XPathDocument xpdoc = new XPathDocument( Server.MapPath("people.xml") );
 8    XPathNavigator nav = xpdoc.CreateNavigator();
 9    XPathExpression expr = nav.Compile("descendant::PEOPLE/PERSON");
10    XPathNodeIterator iterator = nav.Select(expr);
11    ArrayList NodeValues = new ArrayList();
12
13    while (iterator.MoveNext())
14        NodeValues.Add(iterator.Current.ToString());
15
16    XMLNodeListBox.DataSource = NodeValues;
17    XMLNodeListBox.DataBind();
18}

五.通过XSL显示XML文件 

 1/**//// <summary>
 2/// 通过XSL显示XML文件
 3/// </summary>
 4private void DisplayXML()
 5{
 6    System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
 7    xmldoc.Load(Server.MapPath("user.xml"));
 8    System.Xml.Xsl.XslTransform xmltrans = new System.Xml.Xsl.XslTransform();
 9    xmltrans.Load(Server.MapPath("user.xsl"));
10    Xml1.Document = xmldoc;
11    Xml1.Transform = xmltrans;
12} 

 六.验证XML文件 

/**//// <summary>
/// 验证XML文件
/// </summary>
private void ValidateXML()
 
{
    FileStream stream = new FileStream(Server.MapPath("people.xml"), FileMode.Open);
    
      /**////创建XmlValidatingReader类的对象
    XmlValidatingReader vr = new XmlValidatingReader(stream, XmlNodeType.Element, null);
    
      /**////加载XML架构文档
    vr.Schemas.Add(null, Server.MapPath("people.xsd"));
    
      /**////说明验证的方式是根据XML架构
    vr.ValidationType = ValidationType.Schema;
    vr.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);
    
      /**////对文档进行验证
    while(vr.Read());
    
      /**////显示验证过程完成
    Page.Response.Write("<b>Validation finished!<b>");
    
      /**////关闭打开的文件
    stream.Close();
}

private void ValidationHandler(object sender, ValidationEventArgs args)
 
{
 
    /**////显示验证失败的消息
    Page.Response.Write("<b>Validation error: </b>" + args.Message + "<p>");
}

 

 

原创粉丝点击