具有自定义格式的XML编写器 [英] XML writer with custom formatting
问题描述
InvalidOperationException
( Token StartAttribute in state元素内容将导致一个无效的XML文档),如果用于代替下面的评论。 是否有解决方法为XmlWriter或第三方XML支持这个的库?
示例代码(LINQPad语句就绪):
var sb = new StringBuilder();
var settings = new XmlWriterSettings {
OmitXmlDeclaration = true,
Indent = true,
IndentChars =,
};
using(var writer = XmlWriter.Create(sb,settings)){
writer.WriteStartElement(X);
writer.WriteAttributeString(A,1);
//写入换行符
writer.WriteAttributeString(B,2);
//写入换行符
writer.WriteAttributeString(C,3);
writer.WriteEndElement();
}
Console.WriteLine(sb.ToString());
实际结果:
< XA =1B =2C =3/>
期望的结果(B和C可能不与A对齐 - 很好,/>可以留下与C)一致:
< XA =1
B =2
C =3
/>
您仍然拥有StringBuilder的背景 - 使用它。 :
var sb = new StringBuilder();
var settings = new XmlWriterSettings {
OmitXmlDeclaration = true,
Indent = true,
IndentChars =,
};
using(var writer = XmlWriter.Create(sb,settings)){
writer.WriteStartElement(X);
writer.WriteAttributeString(A,1);
writer.Flush();
sb.Append(\r\\\
);
writer.WriteAttributeString(B,2);
writer.Flush();
sb.Append(\r\\\
);
writer.WriteAttributeString(C,3);
writer.WriteEndElement();
}
Console.WriteLine(sb.ToString());
I need to create a human-readable XML file. XmlWriter seems to be almost perfect for this, but I'd like to insert line breaks or, in general, custom whitespace where I want them. Neither WriteRaw nor WriteWhitespace seem to work between the attributes in an element. The latter looks like it should work (This method is used to manually format your document), but throws InvalidOperationException
(Token StartAttribute in state Element Content would result in an invalid XML document) if used in place of the comments below.
Is there a workaround for XmlWriter or a third-party XML library that supports this?
Example code (LINQPad-statements ready):
var sb = new StringBuilder();
var settings = new XmlWriterSettings {
OmitXmlDeclaration = true,
Indent = true,
IndentChars = " ",
};
using (var writer = XmlWriter.Create(sb, settings)) {
writer.WriteStartElement("X");
writer.WriteAttributeString("A", "1");
// write line break
writer.WriteAttributeString("B", "2");
// write line break
writer.WriteAttributeString("C", "3");
writer.WriteEndElement();
}
Console.WriteLine(sb.ToString());
Actual result:
<X A="1" B="2" C="3" />
Desired result (B and C may be not aligned with A - that's fine, /> can be left on the line with C):
<X A="1"
B="2"
C="3"
/>
You still has the background StringBuilder - use it. :
var sb = new StringBuilder();
var settings = new XmlWriterSettings {
OmitXmlDeclaration = true,
Indent = true,
IndentChars = " ",
};
using (var writer = XmlWriter.Create(sb, settings)) {
writer.WriteStartElement("X");
writer.WriteAttributeString("A", "1");
writer.Flush();
sb.Append("\r\n");
writer.WriteAttributeString("B", "2");
writer.Flush();
sb.Append("\r\n");
writer.WriteAttributeString("C", "3");
writer.WriteEndElement();
}
Console.WriteLine(sb.ToString());
这篇关于具有自定义格式的XML编写器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!