dongluan2612 2014-10-14 23:14
浏览 114
已采纳

使用Go生成XML文件时,如何创建doctype声明?

Go's xml package is excellent and makes dealing with XML very easy. There's one thing I'm not sure how to do: when creating an XML document from a native struct, how do you specify the doctype?

For example, these structs:

type Person struct {
    XMLName    xml.Name `xml:"person"`
    FirstName  string   `xml:"firstName"`
    MiddleName string   `xml:"middleName"`
    LastName   string   `xml:"lastName"`
    Age        int64    `xml:"age"`
    Skills     []Skill  `xml:"skills"`
}

type Skill struct {
    XMLName        xml.Name `xml:"skill"`
    Name           string   `xml:"skillName"`
    YearsPracticed int64    `xml:"practice"`
}

Will generate something like this XML:

<person>
    <firstName>Bob</firstName>
    <middleName></middleName>
    <lastName>Jones</middleName>
    <age>23</age>
    <skills>
        <skill>
            <skillName>Cooking</skillName>
            <practice>3</practice>
        </skill>
        <skill>
            <skillName>Basketball</skillName>
            <practice>4</practice>
        </skill>
    </skills>
</person>

Which is great, but what do I do to get this:

<?xml version="1.0" encoding="UTF-8"?>
<person>
    <firstName>Bob</firstName>
    <middleName></middleName>
    ...

It almost seems too simple, but is this a matter of doing a string append?

And, on the reverse, how would Go's XML parser handle a doctype in a block of text that you wanted to unmarshal into a set of structs? Ignore it?

  • 写回答

1条回答 默认 最新

  • dongyi7041 2014-10-15 03:26
    关注

    Simply append your marshalled bytes to the header. As seen in the XML Package Source, a generic header is included:

    const (
        // A generic XML header suitable for use with the output of Marshal.
        // This is not automatically added to any output of this package,
        // it is provided as a convenience.
        Header = `<?xml version="1.0" encoding="UTF-8"?>` + "
    "
    )
    

    So, this would do it:

    myString, err := xml.MarshalIndent(...) // abbreviated here
    myString = []byte(xml.Header + string(myString))
    

    A working example I'd found (not my code) available at: http://play.golang.org/p/Rbfb717tvh

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大