解组包含混合内容的XML标记(例如CDATA,其他标记)

问题描述 投票:3回答:1

尝试解组xml文件,如:

<Element>
    <![CDATA[hello]]>
    <image>some_url_here</image>
    <![CDATA[world]]>
    mixed content here
</Element>

Element标签内部有不同类型的数据,我如何将这个xml解组为如下结构:

type XMLElement struct {
    XMLName xml.Name `xml:"Element"`
    CDatas []string `....`
    Image string `...`
    PlainText string `...`
}

或者任何其他结构,这个xml可以被解组。

xml go unmarshalling cdata
1个回答
0
投票

这个解决方案不太好,因为xmlqueryCDATA元素作为TEXT节点类型,但我认为它简单易用,它使用XPath查询。

package main

import (
    "fmt"
    "strings"

    "github.com/antchfx/xmlquery"
)

func main() {
    s := `<?xml version="1.0" encoding="UTF-8"?><Element>
<![CDATA[hello]]>
<image>some_url_here</image>
<![CDATA[world]]>
</Element>
`
    doc, err := xmlquery.Parse(strings.NewReader(s))
    if err != nil {
        panic(err)
    }
    elem := xmlquery.FindOne(doc, "//Element")
    for n := elem.FirstChild; n != nil; n = n.NextSibling {
        if n.Data == "image" {
            fmt.Printf("image: %s\n", n.InnerText())
        } else if n.Type == xmlquery.TextNode {
            if len(strings.TrimSpace(n.InnerText())) == 0 {
                // skip it because its' empty node
            } else {
                fmt.Printf("cdata: %s\n", n.InnerText())
            }
        }
    }
    // or using query expression
    image := xmlquery.FindOne(doc, "//image")
    fmt.Printf("image: %s\n", image.InnerText())
}

© www.soinside.com 2019 - 2024. All rights reserved.