我的第一个问题,请耐心等待。基本上,我的问题是:我正在为一种内部语言构建一个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实现,这可能吗?
到目前为止,我已经尝试了以下内容(从XmlDocument中获得带换行符的缩进XML的最简单方法是什么?)
static public string Beautify(this XmlDocument doc)
{
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NewLineChars = "rn",
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代码运行结果,然后再次用正确的换行符替换换行符。
更新:考虑到这一点,您可能需要将nn
替换为'\n',但您已经大致了解了。
基于Mark的好建议,这将美化XML字符串(但代码不是很漂亮):
class Program
{
static void Main(string[] args)
{
string test = @"<?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>";
string output = Test.BeautifyXML(test);
Console.Write(output);
Console.ReadLine();
}
}
static class Test {
static public string BeautifyXML(this string docString)
{
docString = Regex.Replace(docString.Replace("r", "<r></r>").Replace("n", "<n></n>"),@"?>(<r></r><n></n>)*", "?>");
XmlDocument doc = new XmlDocument();
doc.LoadXml(docString);
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NewLineChars = "rn",
NewLineHandling = NewLineHandling.Replace
};
using (XmlWriter writer = XmlWriter.Create(sb, settings))
{
doc.Save(writer);
}
return Regex.Replace(sb.ToString().Replace("rn", ""), @"<r></r>( )*<n></n>", "rn").Replace("?>", "?>rn");
}
}
输出:
<?xml version="1.0" encoding="utf-16"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
这可能对有用
而不是
NewLineHandling = NewLineHandling.Replace
使用
NewLineHandling = NewLineHandling.None
None
设置告诉XmlWriter
保持输入不变。当您不需要任何新行处理时,将使用此设置。