这是我的第一个问题,请耐心等待。基本上,我的问题是: 我正在为一种内部语言构建一个 XML IDE。它的一个功能应该是使用一些命令自动缩进 XML。类似于在 Visual Studio 等中发现的内容。
基本上我需要的是把下面的Xml:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
进入:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
那是缩进 - 但别碰别的。这在 C# 中是否可能,而无需从头开始编写算法,即使用 LINQ XDocument 或某些 XmlWriter 实现?
到目前为止我已经尝试了以下方法(来自 What is the simplest way to get indented XML with line breaks from XmlDocument? )
static public string Beautify(this XmlDocument doc)
{
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
doc.Save(writer);
}
return sb.ToString();
}
但这会删除换行符并给我:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
提前感谢任何提出意见或回答的人。
最佳答案
我会尝试用自定义标签替换所有换行符(例如 <newline></newline>
,通过现有的 Beautify 代码运行结果,然后再次用适当的换行符替换换行符标签。
更新:考虑更多,您可能需要替换 \n\n
用 '\n',但你明白了一般的想法。
关于c# - 缩进 XML,但保持其他一切不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34756780/