使用Go的xml包编组DIDL-Lite

时间:2012-05-30 08:02:55

标签: xml go

以下是DIDL-Lite

中的示例UPnP AV ContentDirectory v2 Service Template XML文档
<?xml version="1.0" encoding="UTF-8"?>
<DIDL-Lite
 xmlns:dc="http://purl.org/dc/elements/1.1/"
 xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"
 xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
   urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/
    http://www.upnp.org/schemas/av/didl-lite-v2-20060531.xsd
   urn:schemas-upnp-org:metadata-1-0/upnp/
    http://www.upnp.org/schemas/av/upnp-v2-20061231.xsd">
   <item id="18" parentID="13" restricted="0">
      ...
   </item>
</DIDL-Lite>

如何使用Go's xml package转换为?更具体地说:

  1. 如何定义名称空间前缀,例如xmlns:dcxmlns:upnp
  2. 如何在元素上配置多个名称空间?
  3. 如何为属性设置名称空间,例如xsi属性上的schemaLocation前缀?
  4. 作为基础,我有这样的事情:

    type DIDLLite struct {
        XMLName xml.Name `xml:"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/ DIDL-Lite"`
        // ??? namespace prefixes dc, upnp, xsi
        Objects []Object
    }
    

    我还发现了this可能相关的错误。

1 个答案:

答案 0 :(得分:4)

您给的示例是编组的。我假设您要问,“如何将使用xml.Marshal编组的Go数据类型定义为此?”

package main

import (
    "encoding/xml"
    "fmt"
)

type DIDLLite struct {
    XMLName xml.Name
    DC      string   `xml:"xmlns:dc,attr"`
    UPNP    string   `xml:"xmlns:upnp,attr"`
    XSI     string   `xml:"xmlns:xsi,attr"`
    XLOC    string   `xml:"xsi:schemaLocation,attr"`
    Objects []Object `xml:"item"`
}

type Object struct {
    ID         string `xml:"id,attr"`
    Parent     string `xml:"parentID,attr"`
    Restricted string `xml:"restricted,attr"`
}

func main() {
    d := DIDLLite{
        XMLName: xml.Name{
            Space: "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/",
            Local: "DIDL-Lite",
        },
        DC:   "http://purl.org/dc/elements/1.1/",
        UPNP: "urn:schemas-upnp-org:metadata-1-0/upnp/",
        XSI:  "http://www.w3.org/2001/XMLSchema-instance",
        XLOC: `
   urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/
    http://www.upnp.org/schemas/av/didl-lite-v2-20060531.xsd
   urn:schemas-upnp-org:metadata-1-0/upnp/
    http://www.upnp.org/schemas/av/upnp-v2-20061231.xsd`,
        Objects: []Object{{ID: "18", Parent: "13", Restricted: "0"}},
    }
    b, err := xml.MarshalIndent(d, "", "    ")
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(b))
}

输出:

<DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
   urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/
    http://www.upnp.org/schemas/av/didl-lite-v2-20060531.xsd
   urn:schemas-upnp-org:metadata-1-0/upnp/
    http://www.upnp.org/schemas/av/upnp-v2-20061231.xsd">
    <item id="18" parentID="13" restricted="0"></item>
</DIDL-Lite>

可以打印得很漂亮,以符合上面的例子。 xml.MarshallIndent还有点原始。

相关问题