如何在xml序列化中的标记之后创建新行

时间:2012-07-26 02:55:47

标签: c# xml-serialization

我使用xml序列化来创建我的xml片段。每个序列化都不会在最后创建换行符,导致在关闭标记后面打开标记。请参阅下面的示例输出,其中在相同的行打开标记
中遵循关闭标记 如何强制序列化对象在新行中?

    maxmumleewayinticks=Instrument.MasterInstrument.TickSize*2;

    string filename="c:\\temp\\Strategyxmlfile" + DateTime.Now.Ticks + ".xml";
    settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.IndentChars = "  ";
    settings.NewLineChars = "\r\n";
    settings.NewLineHandling = NewLineHandling.Replace;
    settings.OmitXmlDeclaration = true;
    settings.CloseOutput = false;   
    writer= new StreamWriter(filename);

    ns.Add("", "");
   // write and close the bar

   XmlSerializer serializer = new        XmlSerializer(typeof( DecisionBar));

   w =XmlWriter.Create(writer,settings);

   serializer.Serialize(w, decision,ns);

输出:

<DecisionBar EntryOrExit="ENTRY">
  <mfe>0.0001</mfe>
  <mae>-0.0002</mae>
  <bartime>2012-07-25T21:43:00</bartime>
  <frequency>1 MINUTES</frequency>
  <HH7>true</HH7>
  <crossover>true</crossover>
  <currentprofitability>0.0001</currentprofitability>
  <entryPointLong>1.032</entryPointLong>
  <entryPointShort>1.0308</entryPointShort>
  <exitStopFull>1.031</exitStopFull>
  <exitStopPartial>0</exitStopPartial>
 </DecisionBar><DecisionBar> 
  <mfe>0.0001</mfe>
  <mae>-0.0002</mae>
  <bartime>2012-07-25T21:44:00</bartime>
  <frequency>1 MINUTES</frequency>
  <HH7>false</HH7>
  <crossover>false</crossover>
  <currentprofitability>0.0001</currentprofitability>
  <entryPointLong>0</entryPointLong>
  <entryPointShort>0</entryPointShort>
  <exitStopFull>0</exitStopFull>
  <exitStopPartial>0</exitStopPartial>
</DecisionBar>

1 个答案:

答案 0 :(得分:2)

看看here

try
{
    MemberList g = new MemberList("group name");
    g.members[0] = new Member("mem 1");
    g.members[1] = new Member("mem 2");
    g.members[2] = new Member("mem 3");

    StringWriter sw = new StringWriter();
    XmlTextWriter tw = new XmlTextWriter(sw);
    tw.Formatting = Formatting.Indented;
    tw.Indentation = 4;

    XmlSerializer ser = new XmlSerializer(typeof(MemberList));
    ser.Serialize(tw, g);

    tw.Close();
    sw.Close();

    Console.WriteLine(sw.ToString());
}
catch(Exception exc)
{
    Console.WriteLine(exc.Message);
}

这将为您提供所需的结果,虽然它需要一些额外的工作,而不仅仅是在XmlSerializer上指定一些选项。

编辑:有很多变化。我发现了这个Googling;你也可以这样做。