Conserve line breaks when reading multi-line text attribute with LINQ To XML

39 views Asked by At

When reading an XML file with LINQ To XML (System.Xml.Linq), I need to be able to conserve the line breaks in multi-line text attributes. Here's an example XML file.

<?xml version="1.0" encoding="utf-8"?>
<TestRoot>
    <Properties Description="Line 1
Line 2" />
</TestRoot>

Here's the code I tried:

const string xmlPath = @"C:\Blah\Test.xml";
var rootElement = XElement.Load(xmlPath);
var propertiesElement = rootElement.Element("Properties")!;
var descriptionAttribute =
    propertiesElement.Attribute("Description")!;
string description = descriptionAttribute.Value;
Console.WriteLine(description);

Expected output:

Line 1
Line 2

Actual output:

Line 1 Line 2

Note: I see this question is a duplicate. The first answer to the other question works for me. I will leave my question here, as the different wording of its title will provide another route to the answer.

0

There are 0 answers