如何创建在.NET中使用的XmlWriter一个XmlDocument的? [英] How to create a XmlDocument using XmlWriter in .NET?
问题描述
许多.NET函数使用的XmlWriter输出/生成XML。输出到文件/字符串/内存是一个非常操作:
Many .NET functions use XmlWriter to output/generate xml. Outputting to a file/string/memory is a very operation:
XmlWriter xw = XmlWriter.Create(PutYourStreamFileWriterEtcHere);
xw.WriteStartElement("root");
...
有时候,你需要操作生成的XML,因此希望将其加载到一个XmlDocument的或可能需要一个XmlDocument某些其他原因,但你必须使用的XmlWriter生成XML。例如,如果你在输出到XmlWriter的第三方库调用函数而已。
Sometimes , you need to manipulate the resulting Xml and would therefore like to load it into a XmlDocument or might need an XmlDocument for some other reason but you must generate the XML using an XmlWriter. For example, if you call a function in a 3rd party library that outputs to a XmlWriter only.
的事情之一,你可以做的是编写的XML字符串,然后将其加载到你的XmlDocument:
One of the things you can do is write the xml to a string and then load it into your XmlDocument:
StringWriter S = new StringWriter();
XmlWriter xw = XmlWriter.Create(S);
/* write away */
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(S.ToString());
然而,这是低效的 - 首先你序列化所有的XML信息转换成字符串,然后你再解析字符串创建DOM
However this is inefficient - first you serialize all the xml info into a string, then you parse the string again to create the DOM.
你怎么可以指向一个的XmlWriter建立一个XmlDocument的直接?
How can you point an XmlWriter to build a XmlDocument directly?
推荐答案
下面是至少有一个解决方案:
Here's at least one solution:
XmlDocument doc = new XmlDocument();
using (XmlWriter writer = doc.CreateNavigator().AppendChild())
{
// Do this directly
writer.WriteStartDocument();
writer.WriteStartElement("root");
writer.WriteElementString("foo", "bar");
writer.WriteEndElement();
writer.WriteEndDocument();
// or anything else you want to with writer, like calling functions etc.
}
显然声明XpathNavigator给你,当你调用一个XmlWriter的使用appendChild()
Apparently XpathNavigator gives you a XmlWriter when you call AppendChild()
现金去马丁Honnen上:<一href="http://groups.google.com/group/microsoft.public.dotnet.xml/browse%5Fthread/thread/24e4c8d249ad8299?pli=1">http://groups.google.com/group/microsoft.public.dotnet.xml/browse%5Fthread/thread/24e4c8d249ad8299?pli=1
Credits go to Martin Honnen on : http://groups.google.com/group/microsoft.public.dotnet.xml/browse%5Fthread/thread/24e4c8d249ad8299?pli=1
这篇关于如何创建在.NET中使用的XmlWriter一个XmlDocument的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!