3

I need to create a human-readable XML file. XmlWriter seems to be almost perfect for this, but I'd like to insert line breaks or, in general, custom whitespace where I want them. Neither WriteRaw nor WriteWhitespace seem to work between the attributes in an element. The latter looks like it should work (This method is used to manually format your document), but throws InvalidOperationException (Token StartAttribute in state Element Content would result in an invalid XML document) if used in place of the comments below.

Is there a workaround for XmlWriter or a third-party XML library that supports this?

Example code (LINQPad-statements ready):

var sb = new StringBuilder();
var settings = new XmlWriterSettings {
    OmitXmlDeclaration = true,
    Indent = true,
    IndentChars = "  ",
};
using (var writer = XmlWriter.Create(sb, settings)) {
    writer.WriteStartElement("X");
    writer.WriteAttributeString("A", "1");
    // write line break
    writer.WriteAttributeString("B", "2");
    // write line break
    writer.WriteAttributeString("C", "3");
    writer.WriteEndElement();
}
Console.WriteLine(sb.ToString());

Actual result:

<X A="1" B="2" C="3" />

Desired result (B and C may be not aligned with A - that's fine, /> can be left on the line with C):

<X A="1"
   B="2"
   C="3"
/>
3
  • human-readable XML file: smells like spec creep!
    – Gusdor
    Commented Jun 3, 2014 at 7:58
  • @Rawling, forgot to mention - I don't want them all on new lines, just where it makes sense in the context (i.e. only add manually) Commented Jun 3, 2014 at 8:12
  • Oh I see your point! (Just not in time to avoid turning my comment into an answer...)
    – Rawling
    Commented Jun 3, 2014 at 8:12

1 Answer 1

5

You still has the background StringBuilder - use it. :

  var sb = new StringBuilder();
  var settings = new XmlWriterSettings {
    OmitXmlDeclaration = true,
    Indent = true,
    IndentChars = "  ",
  };
  using (var writer = XmlWriter.Create(sb, settings)) {
    writer.WriteStartElement("X");
    writer.WriteAttributeString("A", "1");
    writer.Flush();
    sb.Append("\r\n");
    writer.WriteAttributeString("B", "2");
    writer.Flush();
    sb.Append("\r\n");
    writer.WriteAttributeString("C", "3");
    writer.WriteEndElement();
  }
  Console.WriteLine(sb.ToString());
1
  • Ah yes, haven't thought of that for some reason. Thank you! Commented Jun 3, 2014 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.