如何在XmlWriter上为特定的元素节点设置缩进属性

本文关键字:元素 节点 设置 属性 缩进 XmlWriter | 更新日期: 2023-09-27 17:51:10

抱歉,如果标题令人困惑,这是我想要实现的。我有一个XmlWriter对象,它被创建并传递给一个方法

public static void foo(XmlWriter xw)
{
   xw.WriteStartElement("root");
}
此时XmlWriter已经实例化,Xml声明也已经写好了。现在,在写入根元素之后,我需要将XmlWriter上的缩进属性设置为true(在创建XmlWriter时将其设置为false)。像这样
public static void foo(XmlWriter xw)
{
   xw.WriteStartElement("root");
   // xw.Settings.Indent = true; - I know this won't work
   // continue writing elements...
}

无法找到如何设置缩进的方法。有什么想法吗?

如何在XmlWriter上为特定的元素节点设置缩进属性

使用XmlTextWriter。然后可以将缩进属性设置为要缩进的空格数。http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.indentation.aspx

若要使用缩进属性,则不能使用混合内容http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.indent.aspx

"只要元素不包含混合内容,元素就会缩进。一旦调用WriteString或WriteWhitespace方法写出混合元素内容,XmlWriter就会停止缩进。一旦关闭混合内容元素,缩进就会恢复。"