问题描述
这必须是一个非常简单的问题,但我只是找不到答案.
This has got to be such a simple question but I just can't get the answer.
我有一个XmlNode,我要做的就是将此节点作为字符串输出,并完整保留缩进(制表符或空格)以提供更好的可读性.
I have an XmlNode and all I want to do is output this node, as a string, with indentations (tabs or spaces) intact to provide better readability.
到目前为止,我尝试了XmlWriter,XmlTextWriter,XmlDocument,XmlReader.
So far I tried XmlWriter, XmlTextWriter, XmlDocument, XmlReader.
- 我在XmlDocument中尝试了PreserveWhitespace,但无法获取XmlDocument输出节点.
- 我尝试了XmlTextWriter中的Formatting = Formatting.Indented属性,但是我不知道如何将内容输出为字符串.
将XmlNode输出为不带缩进的字符串很容易.我只是做XmlNode.OuterXml.我如何在其中获得压痕?
To output the XmlNode as string WITHOUT indentation is easy. I just do XmlNode.OuterXml. How do I get the indentations in there?
我想做到这一点而无需遍历XmlNode并使用蛮力添加空格,因为我认为应该有一个更简单的方法.
I want to do this without looping through the XmlNode and using brute force to add whitespace, because I think there should be a simpler way.
谢谢.
对于未来的读者,这是答案:
For future readers, here is the answer:
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转换为FlowDocument,该文件可以显示在RichTextBox中.
The reason I needed to do this was output the node's xml with syntax highlighting. I used AvalonEdit to highlight the xml, outputted the highlighted text to html, then converted the html to a FlowDocument which could be displayed in a RichTextBox.
推荐答案
您在使用XMLTextWriter
的正确路径上,只需要使用StringWriter
作为基本流.这是一些好的答案关于如何完成的.如果您的编码需要为UTF-8,请特别注意第二个答案.
You were on the right path with the XMLTextWriter
, you simply need to use a StringWriter
as the base stream. Here are a few good answers on how this is accomplished. Pay particular attention to the second answer, if your encoding needs to be UTF-8.
如果您需要在多个地方执行此操作,那么编写扩展方法以使XmlNode
上的ToString()
重载是简单的:
If you need to do this in multiple places, it is trivial to write an extension method to overload a ToString()
on XmlNode
:
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#中,如何使用缩进将XmlNode转换为字符串? (无循环)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!