views:

453

answers:

1

I need to save one XmlDocument to file with proper indentation (Formatting.Indented) but some nodes with their children have to be in one line (Formatting.None).

How to achieve that since XmlTextWriter accept setting for a whole document?


Edit after @Ahmad Mageed's resposne:

I didn't know that XmlTextWriter settings can be modified during writing. That's good news.

Right now I'm saving xmlDocument (which is already filled with nodes, to be specific it is .xaml page) this way:

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

It enables indentation in all nodes, of course. I need to disable indentation when dealing with all <Run> nodes.

In your example you write to XmlTextWriter "manually". Is there an easy way to crawl through all xmlDocument nodes and write them to XmlTextWriter so I can detect <Run> nodes? Or do I have to write some kind of recursive method that will go to every child of current node?

+2  A: 

What do you mean by "since XmlTextWriter accept setting for a whole document?" The XmlTextWriter's settings can be modified, unlike XmlWriter's once set. Similarly, how are you using XmlDocument? Please post some code to show what you've tried so that others have a better understanding of the issue.

If I understood correctly, you could modify the XmlTextWriter's formatting to affect the nodes you want to appear on one line. Once you're done you would reset the formatting back to be indented.

For example, something like this:

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();
Ahmad Mageed