You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为XElement添加换行?附现有代码示例

如何让XElement生成的根元素属性单独换行

要实现根元素的每个属性单独换行的效果,你需要借助XmlWriterSettings来控制XML的输出格式——因为XElement默认的ToString()方法会把所有属性压缩到同一行,无法直接拆分属性换行。下面是具体的实现步骤:

1. 保留原有的XElement创建逻辑

先按你原来的代码创建根元素,命名空间和属性定义都不用改:

XNamespace XMLNS = "http://.../impex";
XNamespace xsi = "http://...instance";
string SchemaLocation = "http://.../impex productattributegroup.xsd";

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

2. 配置XmlWriterSettings启用属性换行

核心是设置NewLineOnAttributes = true,这个参数会让每个属性单独占一行,同时开启缩进让格式更美观:

var xmlSettings = new XmlWriterSettings
{
    Indent = true,                  // 启用缩进
    IndentChars = "  ",             // 用两个空格作为缩进(可换成\t)
    OmitXmlDeclaration = true,      // 如果不需要XML声明(<?xml...?>)就设为true
    NewLineOnAttributes = true      // 关键:让每个属性单独换行
};

3. 使用XmlWriter生成格式化后的XML

通过XmlWriter按照配置好的规则输出XML,就能得到你想要的换行效果:

using (var stringWriter = new StringWriter())
using (var xmlWriter = XmlWriter.Create(stringWriter, xmlSettings))
{
    rootElement.WriteTo(xmlWriter);
    xmlWriter.Flush();
    string formattedXml = stringWriter.ToString();
    // 这里可以输出或者保存formattedXml
    Console.WriteLine(formattedXml);
}

最终输出效果

执行后你会得到这样的格式化XML:

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

注意:如果需要保留XML声明(<?xml version="1.0" encoding="utf-16"?>),只需要把OmitXmlDeclaration设为false即可。

内容的提问来源于stack exchange,提问作者ShrnPrmshr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:12:28