Last active
July 1, 2017 12:26
golang NonNamespaceString -- https://github.com/golang/go/issues/14407
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rss | |
import "encoding/xml" | |
// NonNamespaceString is a special kind of string. When unmarshal'ed it | |
// will only unmarshal when there is no namespace. | |
// For more details, see: https://github.com/golang/go/issues/8535 | |
type NonNamespaceString string | |
func (s *NonNamespaceString) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { | |
if start.Name.Space != "" { | |
// We do not want a namespace, so we need to consume it | |
d.Skip() | |
return nil | |
} else { | |
str := "" | |
d.DecodeElement(&str, &start) | |
*s = NonNamespaceString(str) | |
} | |
return nil | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rss | |
import ( | |
"encoding/xml" | |
"io/ioutil" | |
"testing" | |
) | |
func TestNonNamespaceString(t *testing.T) { | |
xmlFile, err := ioutil.ReadFile("with-namespace.xml") | |
if err != nil { | |
t.Fatalf("Error reading resource: %v", err) | |
} | |
c := struct { | |
XMLName xml.Name `xml:"rss"` | |
Channel struct { | |
Link NonNamespaceString `xml:"string"` | |
} `xml:"channel"` | |
}{} | |
xml.Unmarshal(xmlFile, &c) | |
expected := "http://sub2.example.org/" | |
if string(c.Channel.Link) == expected { | |
t.Errorf("Unexpected link: %v; wanted: %v", c.Channel.Link, expected) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<rss xmlns:atom="http://www.w3.org/2005/Atom"> | |
<channel> | |
<atom:link rel='hub' href='http://sub1.example.org'/> | |
<link>http://sub2.example.org/</link> | |
<atom:link rel="search" type="application/opensearchdescription+xml" href="http://sub3.example.org" title="Example" /> | |
</channel> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment