ASP.NET中常用功能代码总结(6)——XML文件操作篇
ASP.NET中常用功能代码总结(6)——XML文件操作篇
整理:Terrylee
一.写入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}
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
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}
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}
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}
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>");
}
/// 验证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>");
}
支持TerryLee的创业产品Worktile
Worktile,新一代简单好用、体验极致的团队协同、项目管理工具,让你和你的团队随时随地一起工作。完全免费,现在就去了解一下吧。
https://worktile.com
Worktile,新一代简单好用、体验极致的团队协同、项目管理工具,让你和你的团队随时随地一起工作。完全免费,现在就去了解一下吧。
https://worktile.com