droyo / go-xml

utility and code-generation libraries for XML
MIT License
304 stars 115 forks source link

xsdgen issue - xmlns in tags #12

Open junghao opened 7 years ago

junghao commented 7 years ago

The tags of go struct generated by xsdgen have unnecessary xmlns. This causes unnecessary xmlns while marshalling into xml. For example, from http://www.fdsn.org/xml/station/fdsn-station-1.0.xsd, one of the generated go struct is like this:

type BaseFilterType struct {
    ResourceId  string    `xml:"resourceId,attr"`
    Name        string    `xml:"name,attr"`
    Items       []string  `xml:",any"`
    Description string    `xml:"http://www.fdsn.org/xml/station/1 Description"`
...
}

When marshalling, the Description will be this:

<Description xmlns="http://www.fdsn.org/xml/station/1"></Description>

The xmlns in elements should be omitted. And only add xmlns in the tag with "attr" of root element.

droyo commented 7 years ago

Just so I understand, would this be an acceptable marshalling?

<BaseFilterType xmlns="http://www.fdsn.org/xml/station/1" name="foo" resourceId="1">
  <Description>blah blah blah</Description>
</BaseFilterType>
droyo commented 7 years ago

The above marshalling should be doable by adding an XMLName attribute to any structs, and removing any duplicate namespaces from the field, e.g.

type BaseFilterType struct {
    XMLName     xml.Name  `xml:"http://www.fdsn.org/xml/station/1 BaseFilterType"`
    ResourceId  string    `xml:"resourceId,attr"`
    Name        string    `xml:"name,attr"`
    Items       []string  `xml:",any"`
    Description string    `xml:"Description"`
}

See https://play.golang.org/p/ek-mHr-zFY . It still has the problem that it could introduce errors when decoding, as there could be multiple "Description" elements with different name spaces.

droyo commented 7 years ago

This also raises an issue I had not considered -- case mismatch in root-level element names. If the type name in the schema was baseFilterType, this package would produce invalid output when marshalling a variable of type BaseFilterType -- we would see <BaseFilterType>...</BaseFilterType>. So the XMLName field seems to be necessary for the case when the case doesn't match.