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, " ");//声明调用文件
xWriter.WriteStartElement("", M_str_fname, "");//引入调用文件
xWriter.WriteEntityRef("Log");
xWriter.WriteEndElement();
xWriter.WriteEndDocument();
xWriter.Flush();
xWriter.Close();
}
}
--------------------next---------------------
阅读(369) | 评论(0) | 转发(0) |