0

I've been looking for a while, but I seem not able to find a solution.. I am building XElement with Linq and everything is being nicely aligned except when I try to linebreak Xelement.Value into multiple lines..

My codes looks like:

var result = new XElement("Items",
new XAttribute("ID", id),
new XElement("ItemsA", $"\n{string.Join(",\n", ItemsA.Select(x => x.Value))}\n"),
new XElement("ItemsB", $"\n{string.Join(",\n", ItemsB.Select(x => x.Value))}\n"));

The output of the result looks like:

<Items ID="123123">
  <ItemsA>
items1a,
items2a,
</ItemsA>
  <ItemsB>
items1b,
items2b,
</ItemsB>
</Items>

my question is - how can I make it format/indent it correctly?

I have tried changing $"\n\t{string.Join(",\n\t", ItemsA.Select(x => x.Value))}\n\t" but then it is tabbed further away then the rest of the tags..

What I am trying to achieve is:

<Items ID="123123">
   <ItemsA>
      items1a,
      items2a,
   </ItemsA>
   <ItemsB>
      items1b,
      items2b,
   </ItemsB>
</Items>

I also tried:

private static XElement FormatXml(XElement input)
        {
            var settings = new XmlWriterSettings();
            settings.Indent = true;

            var builder = new StringBuilder(input.ToString());

            using(var writer = XmlWriter.Create(builder, settings))
            {
                input.WriteTo(writer);
            }
            return input;
        }

but it was no luck either.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Min0
  • 150
  • 1
  • 1
  • 12
  • There are many ways to achieve this. Take a look at the following posts answer for more information: http://stackoverflow.com/questions/1123718/format-xml-string-to-print-friendly-xml-string – Michael Oct 14 '16 at 13:47
  • Did you try without all the '\n's? You should be able to save using result.WriteXml("filename"); – jdweng Oct 14 '16 at 14:10
  • Hey, I tried the approaches suggested in http://stackoverflow.com/questions/1123718/format-xml-string-to-print-friendly-xml-string but I end up getting the same result.. I think the issue is that I want xelement.value be split across multiple lines and that is all it does without allignment.. – Min0 Oct 17 '16 at 08:37

0 Answers0