使用 Xelement 时如何换行

How make line break when working with Xelement

你好,抱歉,如果问题很奇怪,抱歉英语不好。 我的代码:

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());

输出:

需要这样:

问题是每个 I12 节点都必须换行。问题出在哪里?

尝试以下操作:

            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;}
                         
        }

试试下面的方法。

        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(sb.ToString());
        xmlDocument.Save(@"D:\Code2Try\bbb.eip");

XMLDocument 以正确的格式保存。