5

我需要保存一个XmlDocument以适当缩进的文件,(Formatting.Indented)但一些节点及其子节点必须在一行中(Formatting.None)

XmlTextWriter由于接受整个文档的设置,如何实现这一点?


在@Ahmad Mageed 回复后编辑:

我不知道 XmlTextWriter 设置可以在编写过程中修改。那是好消息。

现在我正在以这种方式保存 xmlDocument (它已经充满了节点,具体来说是 .xaml 页面):

XmlTextWriter writer = new XmlTextWriter(filePath, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
xmlDocument.WriteTo(writer);
writer.Flush();
writer.Close();

当然,它可以在所有节点中进行缩进。在处理所有<Run>节点时,我需要禁用缩进。

在您的示例中,您“手动”写入 XmlTextWriter。有没有一种简单的方法来爬取所有 xmlDocument 节点并将它们写入 XmlTextWriter 以便我可以检测<Run>节点?还是我必须编写某种递归方法来处理当前节点的每个子节点?

4

1 回答 1

3

“因为 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();
于 2010-01-10T07:57:05.887 回答