Search code examples
c#stringbuilderxelementxmlwriter

How make line break when working with Xelement


Hello and sorry if question is strange and sorry for bad english. My code:

xws.OmitXmlDeclaration = true;

using (XmlWriter xw = XmlWriter.Create(sb, xws))
{
    string lb = "\r\n";
    XElement I11 = new XElement("I11", lb,
                                new XElement("I11_TIPAS", "2"), lb,
                                new XElement("I11_PAV", "pav"), lb,
                                new XElement("I11_KODAS_IS", "985"), lb,
                                from iseip in eip
                                select new XElement("I12", lb,
              new XElement("DI12_BAR_KODAS", iseip.DI12_BAR_KODAS), lb,
              new XElement("I12_KODAS_SS", iseip.I12_KODAS_SS), lb,
              new XElement("I12_KIEKIS", iseip.I12_KIEKIS), lb,
              new XElement("I12_FRAKCIJA", iseip.I12_FRAKCIJA), lb), lb
        );
    I11.Save(xw);
}
System.IO.File.WriteAllText("bbb.eip", sb.ToString());

Output:

output

Need get like this:

need like this

Problem every I12 node must be in new line. Where is problem?


Solution

  • Try following :

                XmlWriterSettings xws = new XmlWriterSettings();
                xws.OmitXmlDeclaration = true;
                xws.Indent = true;
                List<EIP> eip = new List<EIP>();
                using (XmlWriter xw = XmlWriter.Create("bbb.eip", xws))
                {
                    XElement I11 = new XElement("I11", new object[] {
                                                new XElement("I11_TIPAS", "2"),
                                                new XElement("I11_PAV", "pav"),
                                                new XElement("I11_KODAS_IS", "985")
                    });
                    foreach(var iseip in eip)
                    {
    
                        XElement I12 = new XElement("I12", new object[] {
                              new XElement("DI12_BAR_KODAS", iseip.DI12_BAR_KODAS),
                              new XElement("I12_KODAS_SS", iseip.I12_KODAS_SS),
                              new XElement("I12_KIEKIS", iseip.I12_KIEKIS),
                              new XElement("I12_FRAKCIJA", iseip.I12_FRAKCIJA)
                        });
                        I11.Add(I12);
    
                    }
                    I11.Save(xw);
                }
     
            }
            public class EIP
            {
                public string DI12_BAR_KODAS { get;set;}
                public string I12_KODAS_SS { get;set;}
                public string I12_KIEKIS { get;set;}
                public string I12_FRAKCIJA { get;set;}
                             
            }