1

I try to add linebreaks for an XElement. Here is the tag I need to create at the beginning of my file

<enfinity
 xsi:schemaLocation="http://.../impex 
 productattributegroup.xsd"
 xmlns:xsi="http://...instance"
 xmlns="http://...impex"
 major="6" minor="1" family="enfinity" branch="enterprise" build="0.0.91">

here is the code I have without those linebreaks

 var rootElement =
              new XElement(XMLNS + "enfinity",
              new XAttribute(xsi + "schemaLocation", SchemaLocation),
              new XAttribute(XNamespace.Xmlns + "xsi", XSI),
              new XAttribute("xmlns", XMLNS),
              new XAttribute("major", "6"),
              new XAttribute("minor", "1"),
              new XAttribute("family", "enfinity"),
              new XAttribute("branch", "enterprise"),
              new XAttribute("build", "0.0.91") 
              );

I wonder if anyone knows how to do so?

ShrnPrmshr
  • 353
  • 2
  • 5
  • 17
  • Do you mean you want to see a linebreak between each attribute? – Matthew Nov 09 '20 at 12:49
  • yes attribute and if you see there is one line break for the value of schemalocation as well – ShrnPrmshr Nov 09 '20 at 12:50
  • Attributes are normally on same line as the parent tag. Not sure why you want lone breaks on attributes. – jdweng Nov 09 '20 at 14:20
  • The reason is that the XML should be in that format otherwise it is not useable. and that format is that that line should be broken on those lines – ShrnPrmshr Nov 09 '20 at 14:22

1 Answers1

3

You'll need to use an XmlWriter

XmlWriterSettings settings = new XmlWriterSettings()
{
    Indent = true,
    NewLineOnAttributes = true,
    OmitXmlDeclaration = true,
};

using (XmlWriter writer =
        XmlWriter.Create(
            Console.Out /*substitute with your writer here*/,
            settings)
)
{
    rootElement.WriteTo(writer);
}

<enfinity
  major="6"
  minor="1"
  family="enfinity"
  branch="enterprise"
  build="0.0.91" />
Dmitry Ledentsov
  • 3,620
  • 18
  • 28
  • thanks for your quick answer! I am testing this approach so I will update this thread. but I wonder if you know how to add a line break in the value of an attribute.I have tried \n but it does not work – ShrnPrmshr Nov 09 '20 at 14:00
  • feel free to accept the answer if it helps. I'm not sure why you would want to add a line break within an attribute, and what do you mean by it. If your XML will not be read by humans, indentation is not important. If it will, maybe XML is not the best format. On newlines in attributes, see https://stackoverflow.com/a/2004397/847349 – Dmitry Ledentsov Nov 09 '20 at 15:12
  • 1
    thanks this is what I ended up doing! I was trying to do this with less code change as possible. To answer your question, the reader of the XML wants it in that format. – ShrnPrmshr Nov 09 '20 at 15:26
  • if you have contact with the author of the reader, I'd advise to use a real XML parser, which wouldn't be whitespace-dependent – Dmitry Ledentsov Nov 09 '20 at 16:33