我需要保存一个XmlDocument
以适当的缩进归档(Formatting.Indented)
但有些节点及其子节点必须排在一行(Formatting.None)
.
从那时起如何实现这一目标XmlTextWriter
接受整个文档的设置?
在 @Ahmad Majeed 的回复后编辑:
我不知道XmlTextWriter设置可以在写入过程中修改。那是好消息。
现在我正在这样保存 xmlDocument (它已经充满了节点,具体来说是 .xaml 页面):
XmlTextWriter writer = new XmlTextWriter(filePath, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
xmlDocument.WriteTo(writer);
writer.Flush();
writer.Close();
当然,它可以在所有节点中进行缩进。我需要在处理所有内容时禁用缩进<Run>
nodes.
在您的示例中,您“手动”写入 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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)