XML文件操作篇

一.写入XML文件
第一种
如果你的XML样式是固定的话:
None.gifprivate void Button1_Click(object sender, System.EventArgs e)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
string xmlFilename=CreatXml();
InBlock.gif            Page.Response.ContentType 
= "text/xml";
InBlock.gif            Response.AppendHeader(
"Content-Disposition""attachment; filename=" + HttpUtility.UrlEncode(Server.MapPath(string.Format("Xml/{0}{1}",xmlFilename,".Config"))));
InBlock.gif            Response.WriteFile(Server.MapPath(
string.Format("Xml/{0}{1}",xmlFilename,".Config")));
InBlock.gif            Response.End();
ExpandedBlockEnd.gif        }

None.gif        
//创建XML
None.gif
        public string  CreatXml()
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
string applicationID="Telegnosis.Projects.TeleOA.Web";
InBlock.gif            
string applicationName="Telegnosis.Projects.TeleOA.Web";
InBlock.gif            
string applicationDesc="";
InBlock.gif            
string applicationErrorPageUrl="../Util/Error.aspx";
InBlock.gif            
string applicationRoot="/TeleOA";
InBlock.gif            
string xmlFilename="ApplicationSettings";
InBlock.gif
InBlock.gif            
if(this.txt_NewName.Text!=string.Empty)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                xmlFilename
=this.txt_NewName.Text.Trim();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
string path=AppDomain.CurrentDomain.BaseDirectory + "Xml\\" + xmlFilename + ".Config";
InBlock.gif            
if(File.Exists(path))
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                File.Delete(path);
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            StreamWriter sw 
= File.CreateText(path);
InBlock.gif            sw.WriteLine(
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
InBlock.gif            sw.WriteLine(
"<ApplicationConfiguration>");
InBlock.gif            sw.WriteLine(
"<xmlSerializerSection type=\"Telegnosis.Framework.Configuration.Application.ApplicationSettings, Telegnosis.Framework.Configuration, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\">");
InBlock.gif            sw.WriteLine(
"<ApplicationSettings xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"    xmlns=\"Telegnosis.Framework.Configuration\">");
InBlock.gif
            sw.WriteLine("<Application ID=\""+applicationID+"\" Name=\""+applicationName+"\" Desc=\""+applicationDesc+"\" Root=\""+applicationRoot+"\" ErrorPageUrl=\""+applicationErrorPageUrl+"\">");
InBlock.gif        
InBlock.gif            DataTable dt
=GetDataSet();
InBlock.gif            
int count=dt.Rows.Count;
InBlock.gif            
for(int i=0;i<count;i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if(dt.Rows[i][2]!=null)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif
InBlock.gif                        dt.Rows[i][
2]=dt.Rows[i][2].ToString().Replace("",",");
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
string[] cs =dt.Rows[i][2].ToString().Split(new char[] dot.gif',' });
InBlock.gif
InBlock.gif                    
if(cs.Length>1)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
forint j=0;j<cs.Length;j++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            
string str ="<Url Path=\""+cs[j]+"\"     Title=\""+dt.Rows[i][0]+"\"  ResourceID=\""+dt.Rows[i][1]+"\""+"  />";
InBlock.gif                            sw.WriteLine(str);
ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockEnd.gif                    }

InBlock.gif                    
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
string str ="<Url Path=\""+dt.Rows[i][2]+"\"     Title=\""+dt.Rows[i][0]+"\"  ResourceID=\""+dt.Rows[i][1]+"\""+"  />";
InBlock.gif                        sw.WriteLine(str);
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
string str ="<Url Path=\""+dt.Rows[i][2]+"\"     Title=\""+dt.Rows[i][0]+"\"  ResourceID=\""+dt.Rows[i][1]+"\""+"  />";
InBlock.gif                    sw.WriteLine(str);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            sw.WriteLine(
"</UrlList>");
InBlock.gif            sw.WriteLine(
"</Application>");
InBlock.gif            sw.WriteLine(
"</ApplicationSettings>");
InBlock.gif            sw.WriteLine(
"</xmlSerializerSection>");
InBlock.gif            sw.WriteLine(
"</ApplicationConfiguration>");
InBlock.gif            sw.Close();
InBlock.gif            
return xmlFilename;
ExpandedBlockEnd.gif        }

None.gif        
public DataTable GetDataSet()
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            SqlConnection conn
=new SqlConnection(Connectionstring);    
InBlock.gif            DataSet ds
=new DataSet();
InBlock.gif            SqlDataAdapter da
=new SqlDataAdapter("SELECT  ResourceName as Title,ResourceID  ,ResourceDesc  as Path FROM  tb_Resource WHERE ResourceType=0 ",conn);
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                conn.Open();
InBlock.gif                da.Fill(ds,
"xml");
InBlock.gif                conn.Close();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch(Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw(ex);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
return ds.Tables["xml"];
ExpandedBlockEnd.gif        }
第二种
 1 /**/ /// <summary>
 2/// 写入XML文件
 3/// </summary>

 4 private  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.55.549020000);
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
32 private  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>

 4 private  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>

 4 private  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>

 4 private  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>
 4 private  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>");
}
 

转载于:https://www.cnblogs.com/gjahead/archive/2007/05/15/747226.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值