1

I have been trying to use different Go packages for validating xml against xsd and no luck in efficiently using them.

github.com/goxmpp/xml

github.com/lestrrat-go/libxml2

github.com/go-xmlpath/xmlpath

github.com/metaleap/go-xsd/types

I either get compilation failures or unable to install the required dependencies.

Can anyone please provide a package available in Go and also a working example to test any xml against specified schema definition file (xsd)?

user923499
  • 305
  • 1
  • 6
  • 18

1 Answers1

2

Here are a few packages that you can use to validate XML against XSD in Go:

xsdvalidate is a package that uses libxml2 to validate XML. It is a good choice if you need to validate XML quickly and efficiently.

go-xsd is another package that uses libxml2 to validate XML. It is a bit more complex to use than xsdvalidate, but it offers more features.

xmlpath is a package that can be used to parse and validate XML. It is a good choice if you need to do more complex validations, such as checking for the presence of specific elements or attributes.

Here is a code example using xsdvalidate:

package main

import (
    "fmt"
    "github.com/terminalstatic/go-xsd-validate"
)

func main() {
    // Load the XSD file.
    xsdHandler, err := xsdvalidate.NewXsdHandlerFromFile("my_schema.xsd")
    if err != nil {
        panic(err)
    }

    // Load the XML document.
    xmlData, err := ioutil.ReadFile("my_xml.xml")
    if err != nil {
        panic(err)
    }

    // Validate the XML document against the XSD.
    err = xsdHandler.Validate(xmlData)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("XML document is valid")
    }
}

If you want an example for other packages please lemme know, then I can put something.

Md Kamruzzaman
  • 346
  • 1
  • 8
  • Thanks! I get compile error, NewXsdHandlerFromFile not declared by package xsdvalidate and also runtime error, # pkg-config --cflags -- libxml-2.0 pkg-config: exec: "pkg-config": executable file not found in %PATH% – user923499 Aug 03 '23 at 10:45
  • now issue solved? – Md Kamruzzaman Aug 06 '23 at 16:06