首页 > 解决方案 > 为 XElement 添加换行符

问题描述

我尝试为 XElement 添加换行符。这是我需要在文件开头创建的标签

<enfinity
 xsi:schemaLocation="http://.../impex 
 productattributegroup.xsd"
 xmlns:xsi="http://...instance"
 xmlns="http://...impex"
 major="6" minor="1" family="enfinity" branch="enterprise" build="0.0.91">

这是我没有那些换行符的代码

 var rootElement =
              new XElement(XMLNS + "enfinity",
              new XAttribute(xsi + "schemaLocation", SchemaLocation),
              new XAttribute(XNamespace.Xmlns + "xsi", XSI),
              new XAttribute("xmlns", XMLNS),
              new XAttribute("major", "6"),
              new XAttribute("minor", "1"),
              new XAttribute("family", "enfinity"),
              new XAttribute("branch", "enterprise"),
              new XAttribute("build", "0.0.91") 
              );

我想知道是否有人知道该怎么做?

标签: c#xml

解决方案


你需要使用一个XmlWriter

XmlWriterSettings settings = new XmlWriterSettings()
{
    Indent = true,
    NewLineOnAttributes = true,
    OmitXmlDeclaration = true,
};

using (XmlWriter writer =
        XmlWriter.Create(
            Console.Out /*substitute with your writer here*/,
            settings)
)
{
    rootElement.WriteTo(writer);
}

↓</p>

<enfinity
  major="6"
  minor="1"
  family="enfinity"
  branch="enterprise"
  build="0.0.91" />

推荐阅读