gpt4 book ai didi

c# - 在 C# 中,如何将 XmlNode 转换为带有缩进的字符串? (没有循环)

转载 作者:IT王子 更新时间:2023-10-29 04:38:28 25 4
gpt4 key购买 nike

这一定是一个如此简单的问题,但我就是找不到答案。

我有一个 XmlNode,我想做的就是输出这个节点,作为一个字符串,缩进(制表符或空格)完好无损以提供更好的可读性。

到目前为止,我尝试了 XmlWriter、XmlTextWriter、XmlDocument、XmlReader。

  • 我在 XmlDocument 中尝试了 PreserveWhitespace,但无法让 XmlDocument 输出我的节点。
  • 我尝试了 XmlTextWriter 中的 Formatting = Formatting.Indented 属性,但我不知道如何将内容输出到字符串。

将 XmlNode 输出为不缩进的字符串很容易。我只是做 XmlNode.OuterXml。我如何获得那里的缩进?

我想在不循环遍历 XmlNode 和使用蛮力添加空格的情况下执行此操作,因为我认为应该有更简单的方法。

谢谢。

编辑:对于 future 的读者,这里是答案:

  var xmlNode = is some object of type XmlNode

using (var sw = new StringWriter())
{
using (var xw = new XmlTextWriter(sw))
{
xw.Formatting = Formatting.Indented;
xw.Indentation = 2; //default is 1. I used 2 to make the indents larger.

xmlNode.WriteTo(xw);
}
return sw.ToString(); //The node, as a string, with indents!
}

我需要这样做的原因是输出带有语法高亮的节点的 xml。我使用 AvalonEdit 突出显示 xml,将突出显示的文本输出为 html,然后将 html 转换为可以显示在 RichTextBox 中的 FlowDocument。

最佳答案

您使用 XMLTextWriter 的方法是正确的,您只需要使用 StringWriter 作为基本流。这里是a few good answers关于这是如何实现的。如果您的编码需要为 UTF-8,请特别注意第二个答案。

编辑:

如果您需要在多个地方执行此操作,编写一个扩展方法来重载 XmlNode 上的 ToString() 是微不足道的:

public static class MyExtensions
{
public static string ToString(this System.Xml.XmlNode node, int indentation)
{
using (var sw = new System.IO.StringWriter())
{
using (var xw = new System.Xml.XmlTextWriter(sw))
{
xw.Formatting = System.Xml.Formatting.Indented;
xw.Indentation = indentation;
node.WriteContentTo(xw);
}
return sw.ToString();
}
}
}

关于c# - 在 C# 中,如何将 XmlNode 转换为带有缩进的字符串? (没有循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6442123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com