xml.Unmarshal how to get version of xml?

For example, xml response:

<?xml version="1.0" encoding="UTF-8"?>
<testUser><name>foo</name></testUser>

How to get the version 1.0?

Thanks.

The stdlib “encoding/xml” doesn’t recognize “?xml” as a valid StartElement. So you’ll probably have to use “regexp” to extract the XML version info.

Thanks

Hey @RuiShengYang,

If you know for certain that the header format will be correct, you could use something as simple as this rather than needing to use regular expressions:

package main

import (
	"fmt"
	"log"
)

const xmlStr = `<?xml version="1.0" encoding="UTF-8"?>
<testUser><name>foo</name></testUser>`

func main() {
	var version float32
	_, err := fmt.Sscanf(xmlStr, "<?xml version=\"%f\"", &version)
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Printf("%.1f", version)
}

Edit: You can also use the same Sscanf call (or Fscanf if reading from an io.Reader), to obtain the encoding from the header as well if that’s something you want:

package main

import (
	"fmt"
	"log"
)

var xmlStr = `<?xml version="1.0" encoding="UTF-8"?>
<testUser><name>foo</name></testUser>`

func main() {
	var version float32
	var encoding string
	_, err := fmt.Sscanf(xmlStr, "<?xml version=\"%f\" encoding=%q", &version, &encoding)
	if err != nil {
		log.Fatalln(err)
	}
	fmt.Printf("version: %.1f, encoding: %s\n", version, encoding)
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.