本文介绍了注入一个XML字符串转换成的XmlWriter当XML缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XmlTextWriter的书面文件,并使用该文本编写一个的XmlWriter。本文作者是设置为输出制表缩进XML:

I have an XmlTextWriter writing to a file and an XmlWriter using that text writer. This text writer is set to output tab-indented XML:

XmlTextWriter xtw = new XmlTextWriter("foo.xml", Encoding.UTF8);
xtw.Formatting = Formatting.Indented;
xtw.IndentChar = '\t';
xtw.Indentation = 1;

XmlWriter xw = XmlWriter.Create(xtw);



每杰夫的MSDN链接更改:

Changed per Jeff's MSDN link:

XmlWriterSettings set = new XmlWriterSettings();
set.Indent = true;
set.IndentChars = "\t";
set.Encoding = Encoding.UTF8;

xw = XmlWriter.Create(f, set);

这不会改变最终的结果。

This does not change the end result.


现在我是一个任意深度在我的XmlWriter和我收到来自其他地方的XML字符串(即我无法控制),这是一个单行,非缩进的XML。如果我叫xw.WriteRaw(),则该字符串逐字注入并没有按照我的缩进我想要的。

Now I'm an arbitrary depth in my XmlWriter and I'm getting a string of XML from elsewhere (that I cannot control) that is a single-line, non-indented XML. If I call xw.WriteRaw() then that string is injected verbatim and does not follow my indentation I want.

...
string xml = ExternalMethod();
xw.WriteRaw(xml);
...

从本质上讲,我希望有一个WriteRaw将解析XML字符串,并通过所有的WriteStartElement等,以便它能够按照XmlTextWriter中的设置,重新格式化。

Essentially, I want a WriteRaw that will parse the XML string and go through all the WriteStartElement, etc. so that it gets reformatted per the XmlTextWriter's settings.

我的preference是一种与设置我已经有了,并要做到这一点做到这一点,而无需重新加载最终的XML只是重新格式化。我还preFER不解析XML字符串的XmlReader的喜欢,然后模仿其发现到我的XmlWriter(非常非常手动过程)。

My preference is a way to do this with the setup I already have and to do this without having to reload the final XML just to reformat it. I'd also prefer not to parse the XML string with the likes of XmlReader and then mimic what it finds into my XmlWriter (very very manual process).

在本月底我宁愿有不止一个跟随我的preferences一个简单的解决方案。 (最好的解决办法,自然是简单的,遵循我的preferences。)

At the end of this I'd rather have a simple solution than one that follows my preferences. (Best solution, naturally, would be simple and follows my preferences.)

推荐答案

如何使用的XmlReader读取XML作为XML节点?

How about using a XmlReader to read the xml as xml nodes?

string xml = ExternalMethod();
XmlReader reader =  XmlReader.Create(new StringReader(xml));
xw.WriteNode(reader, true);

这篇关于注入一个XML字符串转换成的XmlWriter当XML缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 01:05