在XElement.ToString结果中的XAttributes之间输入换行符/回车符

Nic*_*sen 4 .net c# xelement

是否无法在XElement.ToString生成的xml字符串中的属性之间显示换行符?

以下不起作用 - 它保留了换行符,但是将它们放在所有属性之下,所以只有4/5个空行:

new XElement("options", new XText("\r\n"),
    new XAttribute("updated", Updated.XmlTime()), new XText("\r\n"),
    new XAttribute("color", Color), new XText("\r\n"),
    new XAttribute("puppies", Puppies), new XText("\r\n"),
    new XAttribute("isTrue", IsTrue), new XText("\r\n"),
    new XAttribute("kitties", Kitties ?? "")),
Run Code Online (Sandbox Code Playgroud)

MiM*_*iMo 6

你可以用一个XmlWriter.试试这个:

public static string ToStringFormatted(this XElement xml)
{
  XmlWriterSettings settings = new XmlWriterSettings();
  settings.Indent = true;
  settings.NewLineOnAttributes = true;
  StringBuilder result = new StringBuilder();
  using (XmlWriter writer = XmlWriter.Create(result, settings)) {
    xml.WriteTo(writer);
  }
  return result.ToString();
} // ToStringFormatted
Run Code Online (Sandbox Code Playgroud)

然后

var xml =new XElement("options",
    new XAttribute("updated", "U"),
    new XAttribute("color", "C"),
    new XAttribute("puppies", "P"),
    new XAttribute("isTrue", "I"),
    new XAttribute("kitties", "K")
 );
 Console.WriteLine(xml.ToStringFormatted());
Run Code Online (Sandbox Code Playgroud)

产生这个:

<options
  updated="U"
  color="C"
  puppies="P"
  isTrue="I"
  kitties="K" />
Run Code Online (Sandbox Code Playgroud)

您可以使用各种XmlWriterSettings属性进行不同的格式设置.