3

My goal is to indent manually written XML document programmatically using C# code.

At the moment I'm indenting it using XmlWriter as specified here.

But I still have two problems:

  1. After indentation all line breaks disappear (I do want to preserve artificial line break inside the XML document).
  2. Xml elements which has both text node and sub-elements - are merged to one line. For example:
<element>text
  <subElement></subElement>
</element>

will be indented to this:

<element>text<subElement></subElement></element>

I guess both of the above problems are actually the same problem.

Community
  • 1
  • 1
Nir
  • 1,836
  • 23
  • 26
  • Why do you want this? Just to look “good”? There's no semantic reason for such formatting. Line breaks are interpreted as whitespace. – Ondrej Tucny Nov 14 '13 at 11:28
  • To preserve the XML readability: It is written by humans and also read by them. Sometimes it is much easier to understand XML with line breaks. – Nir Nov 14 '13 at 12:09
  • You would be better giving the humans a pretty-printer and leaving the actual document alone. – John Saunders Dec 27 '13 at 02:17

2 Answers2

1

Inserting whitespace into an XML document, in general, risks changing the semantics of the document.

However, if you really want to indent lines by XML nesting (with no reflow), the serializers that come with most XML parsers can be configured to do it.

Or you could put the document through an XSLT stylesheet which is configured to do indentation.

Either of those approaches would be simpler than writing it yourself, and unless I've missed something in your problem description they should do what you need.

keshlam
  • 7,931
  • 2
  • 19
  • 33
1

If you are using XmlWriter you can create a new XmlWriterSettings object to pass your settings. Here you can set the indentation, NewLineHandling, and many other useful things.

        XmlWriterSettings set = new XmlWriterSettings();
        set.NamespaceHandling = NamespaceHandling.OmitDuplicates;
        set.OmitXmlDeclaration = true;
        set.DoNotEscapeUriAttributes = false;
        set.Indent = true;
        set.NewLineChars = "\n";
        set.IndentChars = "\t";
        set.NewLineHandling = NewLineHandling.None;
        // Make any other changes... up to you

        XmlWriter writer = XmlWriter.Create(Console.Out, set);
        // You can use your writer with the passed settings
Attila
  • 3,206
  • 2
  • 31
  • 44