Search code examples
xmlgordf

How to read XML namespaces attribute in RDF xml file using go


I'm tring to parse following XML file :

<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:eu="http://iec.ch/TC57/CIM100-European#"
    xmlns:md="http://iec.ch/TC57/61970-552/ModelDescription/1#"
    xmlns:cim="http://iec.ch/TC57/CIM100#" > 
  <md:FullModel rdf:about="urn:uuid:52a409c9-72d8-4b5f-bf72-9a22ec9353f7">
   ......

by using go xml.NewDecoder(file).Decode(&model) method. I'm able to get all 'FullModel' and all following items, however I cannot figure out how to get those namespaces strings values: xmlns:rdf, xmlns:eu ...

My code: https://go.dev/play/p/qF_2er47_3R

What wrong with my code?


Solution

  • To generate Go structs from XML you can use generators, for example miku/zek. There are also online version. This code should work as expected: https://go.dev/play/p/xUShK1Wpk8g

    Your root node is RDF and FullModel its child node, but your described FullModel on the same level as RDF in your structs.

    If you need to set a name for root node you can use xml.Name struct field type. According to the documentation for encoding/xml:

    The name for the XML elements is taken from, in order of preference:

    the tag on the XMLName field, if the data is a struct the value of the XMLName field of type Name the tag of the struct field used to obtain the data the name of the struct field used to obtain the data the name of the marshaled type

    Your code:

    type RDF struct {
        Rdf string `xml:"rdf,attr"`
        Eu  string `xml:"eu,attr"`
        Md  string `xml:"md,attr"`
        Cim string `xml:"cim,attr"`
    }
    
    type File_model struct {
        RDF   RDF       `xml:"RDF"`
        Model FullModel `xml:"FullModel"`
    }
    

    Generated struct:

    type RDF struct {
        XMLName   xml.Name `xml:"RDF"`
        Text      string   `xml:",chardata"`
        Rdf       string   `xml:"rdf,attr"`
        Eu        string   `xml:"eu,attr"`
        Md        string   `xml:"md,attr"`
        Cim       string   `xml:"cim,attr"`
        FullModel struct {
            Text                      string `xml:",chardata"`
            About                     string `xml:"about,attr"`
            ...
        } `xml:"FullModel"`
        AccumulatorLimit struct {
            Text                        string `xml:",chardata"`
            ID                          string `xml:"ID,attr"`
            ...
    }