C#操作XML文件总结篇
要对XML文件进行操作,须要声明以下命名空间:
using System.Xml;
一、检查指定XML文件是否存在
System.IO.File.Exists(文件路径及名称);
二、利用C#编程创建XML文件
我在网上找到了这样的两段代码:
代码一:
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode;
XmlElement xmlelem;
XmlElement xmlelem2;
XmlText xmltext;
//加入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文件格式很乱,我不知道怎样调整格式,知道的朋友请赐教。
代码二:
string FileName =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";
XmlDocument doc = 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);
一.写入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 Nodues = 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 Nodues.Add(personElement.FirstChild.Value);
15
16 XMLNodeListBox.DataSource = Nodues;
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 Nodues = new ArrayList();
9
10 while( reader.Read() )
11 {
12 if( reader.NodeType == XmlNodeType.Element && reader.Name == "NAME" )
13 {
14 reader.Read();
15 Nodues.Add( reader.Value );
16 }
17 }
18
19 XMLNodeListBox.DataSource = Nodues;
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 Nodues = new ArrayList();
12
13 while (iterator.MoveNext())
14 Nodues.Add(iterator.Current.ToString());
15
16 XMLNodeListBox.DataSource = Nodues;
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>");