用xpathnavigator和实体引用
xpathnavigator虽然也是以DOM树方式在内在组织数据但已经过优化可对数据进行修改并且访问灵活对比XMLLOAD()方式在效率上提升了不少
在追加时采用实体引用这样不会把新XML文件全部载入内存用流的方式追加到文件末尾省资源速度快当文件较大时尤为明显 using SystemXml;
using SystemXmlXPath;
using SystemIO;
class Program
{
static StreamWriter sw = new StreamWriter(@secondtxt true EncodingUTF);
//创建调用的实体 second要写入的文件
static XmlTextWriter xtw = new XmlTextWriter(sw);
static void Main(string[] args)
{
XPathDocument doc = new XPathDocument(@firstxml);
//first第一个文件
XPathNavigator navigator = docCreateNavigator();
navigatorMoveToRoot();
xtwFormatting = FormattingIndented;
CreatFiles(second); //如果secondxml不存在则在此创建
WriteRecursive(navigator); //从根节点开始
xtwFlush();
xtwClose();
}
static private void WriteRecursive(XPathNavigator navigator)
{
if (navigatorHasChildren)
{
navigatorMoveToFirstChild();
WriteNode(navigator);
WriteRecursive(navigator);
navigatorMoveToParent();
while (navigatorMoveToNext())
{
WriteNode(navigator);
WriteRecursive(navigator);
}
if (navigatorMoveToParent() && navigatorName != root)
{
xtwWriteEndElement();
}
}
else
xtwWriteEndElement();
}
static private void WriteNode(XPathNavigator navigator)
{
if (navigatorNodeType == XPathNodeTypeText)
{
xtwWriteString(navigatorValue);
//写文本节点
}
else if (navigatorName != stringEmpty)
{
xtwWriteStartElement(navigatorName);
//写元素节点
}
}
static private void CreatFiles(string M_str_fname)
{
XmlTextWriter xWriter = new XmlTextWriter(M_str_fname + xml EncodingDefault);
xWriterFormatting = FormattingIndented;
xWriterWriteStartDocument();
xWriterWriteComment(M_str_fname);
string name = M_str_fname + txt; //实体文件全名
xWriterWriteDocType(Log null null <!ENTITY Log SYSTEM + name + >);//声明调用文件
xWriterWriteStartElement( M_str_fname );//引入调用文件
xWriterWriteEntityRef(Log);
xWriterWriteEndElement();
xWriterWriteEndDocument();
xWriterFlush();
xWriterClose();
}
}
在vs下调试通过