1

I have an xml file I am reading in that is formatted as such:

<?xml version="1.0" encoding="utf-8"?>
<Screen_Monitoring>
    <Interval>
        0.05
    </Interval>
    <sendCommand>
        <![CDATA[01 30 41 30 41 30 36 02 30 31 44 36 03]]>
    </sendCommand>
</Screen_Monitoring>

I read the xml file into an XDocument object like so:

XDocument xDoc = new XDocument();
xDoc = XDocument.Load(@"C:\MyCode\CONFIGURATION_1NS.xml");

And immediately write it back out like so:

XmlWriterSettings settings = new XmlWriterSettings
{
    Indent = true,
    IndentChars = "    ",
    NewLineChars = "\r\n",
    NewLineHandling = NewLineHandling.Replace
};

using (XmlWriter writer = XmlWriter.Create(@"C:\MyCode\Config_saved.xml", settings))
{
    xDoc.WriteTo(writer);
}

The output does not match the contents of the input file, as the sendCommand element has the value between the sendCommand tags on the same line as the tags, as so:

<?xml version="1.0" encoding="utf-8"?>
<Screen_Monitoring>
    <Interval>
        0.05
    </Interval>
    <sendCommand><![CDATA[01 30 41 30 41 30 36 02 30 31 44 36 03]]></sendCommand>
</Screen_Monitoring>

Unfortunately I am need to produce output xml for a program that may not work properly if the xml itself is completely valid, but it is not formatted how it wants. Is there any easy way to write out the Xml so that it will be formatted with the value on a line separate from the element tags?

Imbajoe
  • 310
  • 3
  • 16
  • Is that program (the consumer) using a custom parser of some sort? Most XML parsers (in my experience, at least) don't care about those kind of formatting issues. – Tim Jul 01 '16 at 17:05
  • Tim, all I can say is... they probably are using some kind of custom parser that doesn't work as well as one would hope. We have had problems in the past with this client using xml files that aren't formatted as it expects. – Imbajoe Jul 01 '16 at 17:29
  • I think there is an answer here : http://stackoverflow.com/questions/7485037/xdocument-text-node-new-line – Haytam Jul 01 '16 at 17:30
  • Ouch. I hate dealing with third parties who believe XML should be customized some how or don't understand standard XML. You have my sympathies :) About the only thing I can think of is to manually tweak the XML you send, but that can a) get tedious and b) cause its own issues at times. – Tim Jul 01 '16 at 17:31

1 Answers1

3

You need to change your LoadOptions to preserve whitespace:

XDocument.Load(@"C:\MyCode\CONFIGURATION_1NS.xml", LoadOptions.PreserveWhitespace);

See this fiddle for a demo - you can see the result is the same as the input. For saving, you should just be able to use doc.Save(path) directly, as the existing whitespace should be preserved on write.

As an aside, you can remove this line, as the new XDocument is thrown away immediately:

var xDoc = new XDocument();
Charles Mager
  • 25,735
  • 2
  • 35
  • 45