首页 > 解决方案 > 使用 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 节点都必须在新行中。问题出在哪里?

标签: c#stringbuilderxelementxmlwriter

解决方案


尝试以下:

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

推荐阅读