我知道如何使用Formatting.indented,但我不想要它,因为这会将每个元素写入新行。我想要的是仅在特定元素之前插入新行。换句话说,我想准确控制何时创建新行。
这可能吗?
您可以使用WriteWhitespace
.
using (var writer = XmlWriter.Create(Console.Out))
{
writer.WriteStartElement("root");
writer.WriteStartElement("child");
writer.WriteWhitespace("n");
writer.WriteStartElement("child-on-new-line");
writer.WriteString("content");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
}
这将输出:
<root><child>
<child-on-new-line>content</child-on-new-line></child></root>
看到这个小提琴。
空格在 xml 中是不在乎的。 别担心。 使用 xml linq 要容易得多:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication42
{
class Program
{
static void Main(string[] args)
{
XElement book = new XElement("book", new object[] {
new XElement("title","Pride And Prejudice")
});
}
}
}