shg*_*shg 5 .net c# xmldocument indentation xmltextwriter
我需要将一个XmlDocument
文件保存到适当的缩进文件中,(Formatting.Indented)
但是一些带有子项的节点必须在一行中(Formatting.None)
.
如何实现这一点,因为XmlTextWriter
接受整个文档的设置?
在@Ahmad Mageed的resposne之后编辑:
我不知道在写入过程中可以修改XmlTextWriter设置.那是好消息.
现在我正在以这种方式保存xmlDocument(已经填充了节点,具体是.xaml页面):
XmlTextWriter writer = new XmlTextWriter(filePath, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
xmlDocument.WriteTo(writer);
writer.Flush();
writer.Close();
Run Code Online (Sandbox Code Playgroud)
当然,它可以在所有节点中实现缩进.我需要在处理所有<Run>
节点时禁用缩进.
在您的示例中,您"手动"写入XmlTextWriter.有没有一种简单的方法来爬行所有xmlDocument节点并将它们写入XmlTextWriter,以便我可以检测<Run>
节点?或者我是否必须编写某种递归方法,这种方法将转发给当前节点的每个子节点?
“因为 XmlTextWriter 接受整个文档的设置”是什么意思?XmlTextWriter 的设置可以修改,这与 XmlWriter 的一次设置不同。同样,您如何使用 XmlDocument?请发布一些代码来展示您所尝试的内容,以便其他人更好地理解该问题。
如果我理解正确,您可以修改 XmlTextWriter 的格式以影响要显示在一行上的节点。完成后,您可以将格式重置为缩进。
例如,这样的事情:
XmlTextWriter writer = new XmlTextWriter(...);
writer.Formatting = Formatting.Indented;
writer.Indentation = 1;
writer.IndentChar = '\t';
writer.WriteStartElement("root");
// people is some collection for the sake of an example
for (int index = 0; index < people.Count; index++)
{
writer.WriteStartElement("Person");
// some node condition to turn off formatting
if (index == 1 || index == 3)
{
writer.Formatting = Formatting.None;
}
// write out the node and its elements etc.
writer.WriteAttributeString("...", people[index].SomeProperty);
writer.WriteElementString("FirstName", people[index].FirstName);
writer.WriteEndElement();
// reset formatting to indented
writer.Formatting = Formatting.Indented;
}
writer.WriteEndElement();
writer.Flush();
Run Code Online (Sandbox Code Playgroud)