Skip to content

Instantly share code, notes, and snippets.

@hellodword
Created May 12, 2024 04:21
Show Gist options
  • Save hellodword/fa97208b0e81baed8a75f8e40fb2ffea to your computer and use it in GitHub Desktop.
Save hellodword/fa97208b0e81baed8a75f8e40fb2ffea to your computer and use it in GitHub Desktop.
package main
import (
"encoding/xml"
"fmt"
"strings"
)
func main() {
// f := os.Stdin
f := strings.NewReader(`<rdf:RDF
xmlns="http://purl.org/rss/1.0/"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:media="http://search.yahoo.com/mrss/"
xml:lang="en-US">
<media:thumbnail height="30" width="30"
url="https://avatars.githubusercontent.com/u/1024025?s=30&amp;v=4" />
</rdf:RDF>`)
var s struct {
XMLName xml.Name
Attributes []xml.Attr `xml:",any,attr,omitempty"`
Thumbnail *struct {
XMLName xml.Name
Attributes []xml.Attr `xml:",any,attr,omitempty"`
} `xml:"thumbnail"`
// XMLNs *xml.Attr `xml:"xmlns,attr,omitempty"`
// Language *xml.Attr `xml:"lang,attr,omitempty"`
// Media *xml.Attr `xml:"xmlns media,attr,omitempty"`
// RDF *xml.Attr `xml:"xmlns rdf,attr,omitempty"`
// DC *xml.Attr `xml:"xmlns dc,attr,omitempty"`
// Content *xml.Attr `xml:"xmlns content,attr,omitempty"`
}
err := xml.NewDecoder(f).Decode(&s)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", s)
{
var nsMap = make(map[string]string)
for i := range s.Attributes {
if s.Attributes[i].Name.Space == "xmlns" && s.Attributes[i].Name.Local != "" {
nsMap[s.Attributes[i].Value] = s.Attributes[i].Name.Local
s.Attributes[i].Name.Local = s.Attributes[i].Name.Space + ":" + s.Attributes[i].Name.Local
s.Attributes[i].Name.Space = ""
}
}
if local, ok := nsMap[s.XMLName.Space]; ok {
s.XMLName.Local = local + ":" + s.XMLName.Local
s.XMLName.Space = ""
}
if s.Thumbnail != nil {
if local, ok := nsMap[s.Thumbnail.XMLName.Space]; ok {
s.Thumbnail.XMLName.Local = local + ":" + s.Thumbnail.XMLName.Local
s.Thumbnail.XMLName.Space = ""
}
}
b, err := xml.Marshal(s)
if err != nil {
panic(err)
}
fmt.Println(string(b))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment