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

如何在XML指定字段中添加换行?Go语言实现遇阻求助

在XML指定字段中添加换行的解决方案

针对你遇到的问题——用\n插入换行仅显示为空格、<br/>被当作文本的情况,以下是几种可行的解决方式:

方式一:使用XML换行实体&#10;

XML中可以用字符实体&#10;表示换行符,直接替换字符串中的\n即可:

type Person struct {
    Name        string `xml:"name"`
    Age         int    `xml:"age"`
    City        string `xml:"city"`
    Description string `xml:"Description"`
}

func main() {
    person := &Person{
        Name: "John Doe",
        Age:  32,
        City: "New York",
    }
    someText := "some text to insert"
    // 用&#10;替换换行符
    person.Description = fmt.Sprintf("Some description here: %v&#10;Second line of content", someText)
    
    // 生成XML的示例代码
    output, err := xml.MarshalIndent(person, "", "  ")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(xml.Header + string(output))
}

生成的XML会是:

<?xml version="1.0" encoding="UTF-8"?>
<Person>
  <name>John Doe</name>
  <age>32</age>
  <city>New York</city>
  <Description>Some description here: some text to insert&#10;Second line of content</Description>
</Person>

XML解析器会将&#10;解析为换行。

方式二:用CDATA包裹内容

如果内容包含特殊字符(比如HTML标签),可以将Description字段标记为CDATA类型,这样内部的换行符会被完整保留:

修改结构体标签:

type Person struct {
    Name        string `xml:"name"`
    Age         int    `xml:"age"`
    City        string `xml:"city"`
    Description string `xml:"Description,cdata"`
}

赋值时直接用\n:

person.Description = fmt.Sprintf("Some description here: %v\nSecond line with <br/> tag", someText)

生成的XML会是:

<?xml version="1.0" encoding="UTF-8"?>
<Person>
  <name>John Doe</name>
  <age>32</age>
  <city>New York</city>
  <Description><![CDATA[Some description here: some text to insert
Second line with <br/> tag]]></Description>
</Person>

CDATA块内的所有内容都会被当作纯文本保留,包括换行和标签。

方式三:设置xml:space="preserve"属性

通过给Description元素添加xml:space="preserve"属性,可以告诉XML解析器保留元素内的所有空白(包括换行)。需要将Description字段定义为嵌套结构体:

// 定义包含文本和xml:space属性的嵌套结构体
type DescriptionContent struct {
    Text  string `xml:",chardata"`
    Space string `xml:"xml:space,attr"`
}

type Person struct {
    Name        string              `xml:"name"`
    Age         int                 `xml:"age"`
    City        string              `xml:"city"`
    Description DescriptionContent `xml:"Description"`
}

赋值时指定属性和文本:

person.Description = DescriptionContent{
    Text:  fmt.Sprintf("Some description here: %v\nAnother line", someText),
    Space: "preserve",
}

生成的XML会是:

<?xml version="1.0" encoding="UTF-8"?>
<Person>
  <name>John Doe</name>
  <age>32</age>
  <city>New York</city>
  <Description xml:space="preserve">Some description here: some text to insert
Another line</Description>
</Person>

这种方式严格遵循XML规范,适合需要严格保留空白格式的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:25:19