问题描述
我有以下结构:
type XMLProduct struct {
XMLName xml.Name `xml:"row"`
ProductId string `xml:"product_id"`
ProductName string `xml:"product_name"`
OriginalPrice string `xml:"original_price"`
BargainPrice string `xml:"bargain_price"`
TotalReviewCount int `xml:"total_review_count"`
AverageScore float64 `xml:"average_score"`
}
然后我使用 encoding / xml
对其进行编码,然后将其显示在网页上。
And I use the encoding/xml
to encode this and then display it on web page.
ProductName
字段必须用<![CDATA []] $ c $括起来c>。但是,如果我将其写为
<![CDATA [+ p.ProductName +]]>
,则<
和>
将转换为& lt;
和& lt
。
The ProductName
field needs to be enclosed with <![CDATA[]]
. But if I write it as <![CDATA[ + p.ProductName + ]]>
, the <
and >
will be translated to <
and >
.
如何以最低的成本创建 CDATA
?
How can I create the CDATA
at minimal cost?
推荐答案
如@Tomalak所述,不支持输出CDATA。
As @Tomalak mentioned, outputting CDATA is not supported.
您可能可以编写![CDATA [
]作为xml标记,随后替换生成的xml中的结束标记。这对您有用吗?它可能不是成本最低但最简单的一种。当然,您可以在下面的示例中将MarshalIndent调用替换为Marshal调用。
You can probably write ![CDATA[
as xml tag and later on replace the closing tag from the resulting xml. Will this work for you? Its probably not the one with minimal costs, but easiest. You can of course replace the MarshalIndent call with just the Marshal call in the example below.
package main
import (
"encoding/xml"
"fmt"
"bytes"
)
type XMLProduct struct {
XMLName xml.Name `xml:"row"`
ProductId string `xml:"product_id"`
ProductName string `xml:"![CDATA["`
OriginalPrice string `xml:"original_price"`
BargainPrice string `xml:"bargain_price"`
TotalReviewCount int `xml:"total_review_count"`
AverageScore float64 `xml:"average_score"`
}
func main() {
prod := XMLProduct{
ProductId: "ProductId",
ProductName: "ProductName",
OriginalPrice: "OriginalPrice",
BargainPrice: "BargainPrice",
TotalReviewCount: 20,
AverageScore: 2.1}
out, err := xml.MarshalIndent(prod, " ", " ")
if err != nil {
fmt.Printf("error: %v", err)
return
}
out = bytes.Replace(out, []byte("<![CDATA[>"), []byte("<![CDATA["), -1)
out = bytes.Replace(out, []byte("</![CDATA[>"), []byte("]]>"), -1)
fmt.Println(string(out))
}
这篇关于如何用go创建xml的CDATA节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!