遍历现有XML文件,同时写入到新文件中. ---(c#)
来源:互联网 发布:什么牌子压力锅好 知乎 编辑:程序博客网 时间:2024/05/18 00:17
用xpathnavigator和实体引用.
xpathnavigator,虽然也是以DOM树方式在内在组织数据,但已经过优化,可对数据进行修改,并且访问灵活,对比XML.LOAD()方式,在效率上提升了不少.
在追加时采用实体引用,这样不会把新XML文件全部载入内存,用流的方式追加到文件末尾,省资源,速度快,当文件较大时尤为明显.
using System.Xml; using System.Xml.XPath; using System.IO;
class Program
{
static StreamWriter sw = new StreamWriter(@"second.txt", true, Encoding.UTF8); //创建调用的实体 ,second---要写入的文件
static XmlTextWriter xtw = new XmlTextWriter(sw);
static void Main(string[] args)
{
XPathDocument doc = new XPathDocument(@"first.xml"); //first---第一个文件
XPathNavigator navigator = doc.CreateNavigator();
navigator.MoveToRoot();
xtw.Formatting = Formatting.Indented;
CreatFiles("second"); //如果second.xml不存在,则在此创建
WriteRecursive(navigator); //从根节点开始
xtw.Flush();
xtw.Close();
}
static private void WriteRecursive(XPathNavigator navigator)
{
if (navigator.HasChildren)
{
navigator.MoveToFirstChild();
WriteNode(navigator);
WriteRecursive(navigator);
navigator.MoveToParent();
while (navigator.MoveToNext())
{
WriteNode(navigator);
WriteRecursive(navigator);
}
if (navigator.MoveToParent() && navigator.Name != "root")
{
xtw.WriteEndElement();
}
}
else
xtw.WriteEndElement();
}
static private void WriteNode(XPathNavigator navigator)
{
if (navigator.NodeType == XPathNodeType.Text)
{
xtw.WriteString(navigator.Value); //写文本节点
}
else if (navigator.Name != string.Empty)
{
xtw.WriteStartElement(navigator.Name); //写元素节点
}
}
static private void CreatFiles(string M_str_fname)
{
XmlTextWriter xWriter = new XmlTextWriter(M_str_fname + ".xml", Encoding.Default);
xWriter.Formatting = Formatting.Indented;
xWriter.WriteStartDocument();
xWriter.WriteComment(M_str_fname);
string name = M_str_fname + ".txt"; //实体文件全名
xWriter.WriteDocType("Log", null, null, " <!ENTITY Log SYSTEM '" + name + "'>");//声明调用文件
xWriter.WriteStartElement("", M_str_fname, "");//引入调用文件
xWriter.WriteEntityRef("Log");
xWriter.WriteEndElement();
xWriter.WriteEndDocument();
xWriter.Flush();
xWriter.Close();
}
}
在vs2008下调试通过.
- 遍历现有XML文件,同时写入到新文件中. ---(c#)
- awk更新现有文件内容并输出到新文件中
- C#:编程写入xml文件
- android解析xml文件,并写入到短信中
- 写入内容到文件中
- object-c把数据写入到文件中
- object-c把数据写入到文件中
- <归档> object-c把数据写入到文件中
- C中将格式化数据写入到文件中操作
- python实例26[将log同时写入文件和显示到UI的控件中]
- C#xml文件的读取写入
- 批处理文件操作:替换文本文件某系字符写入新文件、遍历目录并进行字符串替换、拷贝文件到新目录、去掉文件扩展名
- [C] 将数据写入到文件
- asp.net中写入XML文件
- Opencv中XML文件的写入
- 将XML文件写入数据库中
- MFC中读取写入XML文件
- dos遍历文件夹,把文件写入同一文件中
- GridView中的超链接
- java模拟取款机
- DB2V7存储过程构建环境设置
- 2了解了PYTHON的特点
- VB中MsFlexGrid控件的使用细则
- 遍历现有XML文件,同时写入到新文件中. ---(c#)
- 简单好用的VB字符串加密解密函数
- Struts应用框架介绍
- VB程序界面设计经验点滴
- ASCII 字符表
- 让IE6支持PNG图像透明的底层原理
- 数据中心自动化解决方案供应商 惠普全球第一
- microwindows代码分析 (三)screen driver显示驱动之X11
- 学海无涯