### Install blackfriday-tool
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/github.com/russross/blackfriday/v2/README.md
Install the `blackfriday-tool` command-line utility using `go get`. This also installs blackfriday.
```go
go get github.com/russross/blackfriday-tool
```
--------------------------------
### Install Blackfriday v2
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/github.com/russross/blackfriday/v2/README.md
Use `go get` to install the package in module mode. Alternatively, import it in your package and run `go get`.
```go
go get github.com/russross/blackfriday/v2
```
--------------------------------
### Install XSD2Go CLI
Source: https://github.com/gocomply/xsd2go/blob/master/README.md
Install the XSD2Go command-line tool using `go install`. Ensure you have Go installed and configured.
```shell
go install github.com/gocomply/xsd2go/cli/gocomply_xsd2go@latest
```
--------------------------------
### Install and Use CLI for XSD to Go Conversion
Source: https://context7.com/gocomply/xsd2go/llms.txt
Install the `gocomply_xsd2go` CLI tool using `go install`. Use the `convert` command with the XSD path, Go module path, and output directory. Namespace overrides can be specified using the `--xmlns-override` flag.
```shell
# Install
go install github.com/gocomply/xsd2go/cli/gocomply_xsd2go@latest
# Basic usage
gocomply_xsd2go convert \
path/to/schema.xsd \
github.com/myorg/myapp \
pkg/models
# With xmlns override (rename a Go package derived from a namespace URI)
gocomply_xsd2go convert \
--xmlns-override='http://cpe.mitre.org/language/2.0=cpe_language' \
--xmlns-override='http://www.w3.org/2000/09/xmldsig#=xml_signatures' \
scap_schemas/xccdf_1.2.xsd \
github.com/gocomply/scap \
pkg/scap/models
# Expected console output:
# Processing 'scap_schemas/xccdf_1.2.xsd'
# Parsing: scap_schemas/xccdf_1.2.xsd
# Parsing: scap_schemas/xmldsig-core-schema.xsd
# Generating 'pkg/scap/models/xccdf_1_2/models.go'
# Generating 'pkg/scap/models/xml_signatures/models.go'
```
--------------------------------
### Install strcase Go Package
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/github.com/iancoleman/strcase/README.md
Use this command to install or update the strcase package to the latest version.
```bash
go get -u github.com/iancoleman/strcase
```
--------------------------------
### Install urfave/cli v1
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/github.com/urfave/cli/README.md
Use this command to install the v1 release of the urfave/cli package. Ensure you have Go version 1.18+ installed.
```bash
go get github.com/urfave/cli
```
--------------------------------
### Basic String Case Conversion Examples
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/github.com/iancoleman/strcase/README.md
Demonstrates various string case conversions including snake, screaming snake, kebab, screaming kebab, and delimited cases. Use these functions to standardize string formats.
```go
s := "AnyKind of_string"
```
```go
ToSnake(s)
```
```go
ToSnakeWithIgnore(s, '.')
```
```go
ToScreamingSnake(s)
```
```go
ToKebab(s)
```
```go
ToScreamingKebab(s)
```
```go
ToDelimited(s, '.')
```
```go
ToScreamingDelimited(s, '.', '', true)
```
```go
ToScreamingDelimited(s, '.', ' ', true)
```
```go
ToCamel(s)
```
```go
ToLowerCamel(s)
```
--------------------------------
### Go Function Example
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/github.com/russross/blackfriday/v2/README.md
A simple Go function that returns a boolean value.
```go
func getTrue() bool {
return true
}
```
--------------------------------
### XSD Schema Example
Source: https://context7.com/gocomply/xsd2go/llms.txt
A minimal XSD defining an element and a complex type with an integer field.
```xml
```
--------------------------------
### CLI `gocomply_xsd2go convert` — Command-line conversion
Source: https://context7.com/gocomply/xsd2go/llms.txt
Install and run the CLI to convert an XSD without writing any Go glue code. This provides a convenient way to generate Go types directly from the command line.
```APIDOC
## gocomply_xsd2go convert
### Description
Command-line interface for converting XSD files to Go types.
### Installation
```shell
go install github.com/gocomply/xsd2go/cli/gocomply_xsd2go@latest
```
### Usage
```shell
gocomply_xsd2go convert [--xmlns-override ] [--xmlns-override ]
```
### Parameters
- **xsdPath** (string) - Required - Path to the root XSD file.
- **goModulePath** (string) - Required - Go module import path.
- **outputDir** (string) - Required - Directory where `models.go` files will be created.
- **--xmlns-override** (string) - Optional - Maps an xmlns URI to a custom Go package name. Can be specified multiple times.
### Examples
#### Basic Usage
```shell
gocomply_xsd2go convert \
path/to/schema.xsd \
github.com/myorg/myapp \
pkg/models
```
#### With xmlns overrides
```shell
gocomply_xsd2go convert \
--xmlns-override='http://cpe.mitre.org/language/2.0=cpe_language' \
--xmlns-override='http://www.w3.org/2000/09/xmldsig#=xml_signatures' \
scap_schemas/xccdf_1.2.xsd \
github.com/gocomply/scap \
pkg/scap/models
```
```
--------------------------------
### XSD SimpleType Enumeration Example
Source: https://context7.com/gocomply/xsd2go/llms.txt
Defines an XSD simpleType with enumeration values, which are translated into Go typed string constants.
```xml
```
--------------------------------
### Import urfave/cli in Go
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/github.com/urfave/cli/README.md
Import the urfave/cli package into your Go project to start building command-line applications. This import statement is required for using the package's functionalities.
```go
...
import (
"github.com/urfave/cli"
)
...
```
--------------------------------
### XSD2Go Convert Command Help
Source: https://github.com/gocomply/xsd2go/blob/master/README.md
View help information for the `gocomply_xsd2go convert` command to understand its usage and available options.
```shell
gocomply_xsd2go convert --help
```
--------------------------------
### xsd2go.Convert — Generate Go types from an XSD file
Source: https://context7.com/gocomply/xsd2go/llms.txt
The single public entry point of the library. It creates a `Workspace`, parses the root XSD and all its dependencies, then renders and writes a `models.go` file for every non-empty XML namespace it encounters.
```APIDOC
## xsd2go.Convert
### Description
Generates Go types from an XSD file and its dependencies, writing `models.go` files for each namespace.
### Method Signature
`func Convert(xsdPath string, goModulePath string, outputDir string, xmlnsOverrides []string) error`
### Parameters
- **xsdPath** (string) - Required - Path to the root XSD file.
- **goModulePath** (string) - Required - Go module import path.
- **outputDir** (string) - Required - Directory where `models.go` files will be created.
- **xmlnsOverrides** ([]string) - Optional - Slice of strings for mapping xmlns URIs to custom Go package names (e.g., `"http://www.w3.org/2000/09/xmldsig#=xml_signatures"`).
### Request Example
```go
package main
import (
"log"
"github.com/gocomply/xsd2go/pkg/xsd2go"
)
func main() {
err := xsd2go.Convert(
"schemas/atom.xsd",
"github.com/myorg/myapp",
"pkg/models",
[]string{
"http://www.w3.org/2000/09/xmldsig#=xml_signatures",
},
)
if err != nil {
log.Fatalf("conversion failed: %v", err)
}
}
```
```
--------------------------------
### Parse Generated Go Structs with encoding/xml
Source: https://context7.com/gocomply/xsd2go/llms.txt
Demonstrates how to use the generated Go structs with the standard `encoding/xml` package to unmarshal XML data. Ensure the generated package is imported correctly.
```go
package main
import (
"encoding/xml"
"fmt"
"log"
"strings"
// Generated package from the simple.xsd example above
"github.com/myorg/myapp/pkg/models/simple_schema"
)
const sampleXML = `
42
`
func main() {
var doc simple_schema.Myelement
if err := xml.NewDecoder(strings.NewReader(sampleXML)).Decode(&doc); err != nil {
log.Fatal(err)
}
fmt.Printf("Element: %s, ID: %d\n", doc.XMLName.Local, doc.Id)
// Element: myelement, ID: 42
}
```
--------------------------------
### Basic Markdown Processing
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/github.com/russross/blackfriday/v2/README.md
Process markdown input to HTML output using the default set of popular extensions.
```go
output := blackfriday.Run(input)
```
--------------------------------
### Parse XSD Schemas into an In-Memory Workspace with xsd.NewWorkspace
Source: https://context7.com/gocomply/xsd2go/llms.txt
Use `xsd.NewWorkspace` to parse a root XSD file and all its dependencies into a `Workspace` object. This is useful for programmatic schema inspection. It requires the Go modules path prefix, the root XSD file path, and optional xmlns overrides.
```go
package main
import (
"fmt"
"log"
"github.com/gocomply/xsd2go/pkg/xsd"
)
func main() {
ws, err := xsd.NewWorkspace(
"github.com/myorg/myapp/pkg/models", // Go modules path prefix
"schemas/my-schema.xsd", // root XSD file
[]string{
"http://example.com/ns=my_ns", // optional xmlns overrides
},
)
if err != nil {
log.Fatal(err)
}
for path, schema := range ws.Cache {
fmt.Printf("Schema: %s namespace: %s package: %s empty: %v\n",
path, schema.TargetNamespace, schema.GoPackageName(), schema.Empty())
}
// Schema: schemas/my-schema.xsd namespace: http://example.com/ns package: my_ns empty: false
}
```
--------------------------------
### Basic Markdown Processing with No Extensions
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/github.com/russross/blackfriday/v2/README.md
Process markdown input to HTML output using only the bare Markdown specification, disabling all extensions.
```go
output := blackfriday.Run(input, blackfriday.WithNoExtensions())
```
--------------------------------
### Generate Go Types from Schema with template.GenerateTypes
Source: https://context7.com/gocomply/xsd2go/llms.txt
Renders an embedded Go template against a compiled XSD schema and writes the result as a gofmt-formatted models.go file. Ensure the output directory exists and is correctly specified.
```go
package main
import (
"log"
"github.com/gocomply/xsd2go/pkg/template"
"github.com/gocomply/xsd2go/pkg/xsd"
)
func main() {
ws, err := xsd.NewWorkspace("github.com/myorg/myapp/pkg/models", "schemas/schema.xsd", nil)
if err != nil {
log.Fatal(err)
}
for _, schema := range ws.Cache {
if schema.Empty() {
continue // skip schemas with no exportable types
}
if err := template.GenerateTypes(schema, "pkg/models"); err != nil {
log.Fatalf("generating types for %s: %v", schema.GoPackageName(), err)
}
// Creates: pkg/models//models.go
}
}
```
--------------------------------
### Sanitize Untrusted Markdown Content
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/github.com/russross/blackfriday/v2/README.md
Combine Blackfriday with Bluemonday to sanitize user-generated markdown output, preventing malicious content.
```go
import (
"github.com/microcosm-cc/bluemonday"
"github.com/russross/blackfriday/v2"
)
// ...
unsafe := blackfriday.Run(input)
html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)
```
--------------------------------
### Convert XSD to Go Code
Source: https://github.com/gocomply/xsd2go/blob/master/README.md
Use the `gocomply_xsd2go convert` command to generate Go structs from an XSD file. Specify the XSD file, the Go module import path, and the output directory. The `--xmlns-override` flag can be used to explicitly set Go package names for specific XML namespaces.
```shell
# Acquire latest some XSD file you want to convert - for instance XCCDF 1.2
git clone --depth 1 https://github.com/openscap/openscap
# Parse XSD schema and generate golang structs
./gocomply_xsd2go convert \
--xmlns-override=http://cpe.mitre.org/language/2.0=cpe_language \
.scap_schemas/schemas/xccdf/1.2/xccdf_1.2.xsd \
github.com/gocomply/scap pkg/scap/models
```
--------------------------------
### Integrate XSD2Go with go generate
Source: https://context7.com/gocomply/xsd2go/llms.txt
Embeds XSD2Go commands within a `gen.go` file using `//go:generate` directives to automatically regenerate Go models during the build process. This ensures models are always up-to-date with the XSD definitions.
```go
// file: gen.go (place in the package that owns the generated models)
//go:generate go run github.com/gocomply/xsd2go/cli/gocomply_xsd2go convert schemas/my-schema.xsd github.com/myorg/myapp pkg/models
//go:generate go run github.com/gocomply/xsd2go/cli/gocomply_xsd2go convert --xmlns-override=http://www.w3.org/2000/09/xmldsig#=xml_signatures schemas/signed-schema.xsd github.com/myorg/myapp pkg/models
package models
```
```shell
# Run code generation
go generate ./...
# Output directory structure after generation:
# pkg/models/
# ├── my_ns/
# │ └── models.go
# └── xml_signatures/
# └── models.go
```
--------------------------------
### Configure Custom Acronyms for Case Conversion
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/github.com/iancoleman/strcase/README.md
Globally configure custom acronyms for ToCamel and ToLowerCamel functions to handle specific abbreviations correctly. This must be done before running any conversion functions.
```go
import (
"github.com/iancoleman/strcase"
)
func init() {
// results in "Api" using ToCamel("API")
// results in "api" using ToLowerCamel("API")
strcase.ConfigureAcronym("API", "api")
// results in "PostgreSQL" using ToCamel("PostgreSQL")
// results in "postgreSQL" using ToLowerCamel("PostgreSQL")
strcase.ConfigureAcronym("PostgreSQL", "PostgreSQL")
}
```
--------------------------------
### Unmarshal and Marshal YAML Data in Go
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/gopkg.in/yaml.v3/README.md
Demonstrates unmarshalling YAML data into a Go struct and a map, and then marshalling them back to YAML. Ensure struct fields are public for correct unmarshalling. The `yaml:"flow"` tag controls map formatting.
```Go
package main
import (
"fmt"
"log"
"gopkg.in/yaml.v3"
)
var data = `
a: Easy!
b:
c: 2
d: [3, 4]
`
// Note: struct fields must be public in order for unmarshal to
// correctly populate the data.
type T struct {
A string
B struct {
RenamedC int `yaml:"c"`
D []int `yaml:",flow"`
}
}
func main() {
t := T{}
err := yaml.Unmarshal([]byte(data), &t)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- t:\n%v\n\n", t)
d, err := yaml.Marshal(&t)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- t dump:\n%s\n\n", string(d))
m := make(map[interface{}]interface{})
err = yaml.Unmarshal([]byte(data), &m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- m:\n%v\n\n", m)
d, err = yaml.Marshal(&m)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("--- m dump:\n%s\n\n", string(d))
}
```
--------------------------------
### Generated Go Code for Simple XSD
Source: https://context7.com/gocomply/xsd2go/llms.txt
Go code generated from a simple XSD, including struct definitions for elements and complex types. Note the XMLName tags for marshaling.
```go
// Code generated by https://github.com/gocomply/xsd2go; DO NOT EDIT.
// Models for https://simple.example.com/
package simple_schema
import "encoding/xml"
// Element
type Myelement struct {
XMLName xml.Name `xml:"myelement"`
Id int64 `xml:"id"`
}
// XSD ComplexType declarations
type MyElementType struct {
XMLName xml.Name
Id int64 `xml:"id"`
}
// XSD SimpleType declarations
```
--------------------------------
### Generate Go Types from XSD using xsd2go.Convert API
Source: https://context7.com/gocomply/xsd2go/llms.txt
Use the `xsd2go.Convert` function to generate Go structs from a local XSD file. Specify the XSD path, Go module path, output directory, and optional XML namespace overrides.
```go
package main
import (
"log"
"github.com/gocomply/xsd2go/pkg/xsd2go"
)
func main() {
// Convert a local XSD file to Go structs.
// Args: xsdPath, goModulePath, outputDir, xmlnsOverrides
err := xsd2go.Convert(
"schemas/atom.xsd", // path to root XSD file
"github.com/myorg/myapp", // Go module import path
"pkg/models", // output directory (will be created)
[]string{
// optional: map an xmlns URI to a custom Go package name
"http://www.w3.org/2000/09/xmldsig#=xml_signatures",
},
)
if err != nil {
log.Fatalf("conversion failed: %v", err)
}
// Output: pkg/models//models.go created for each namespace
}
```
--------------------------------
### Parse a Single XSD File with xsd.ReadSchemaFromFile
Source: https://context7.com/gocomply/xsd2go/llms.txt
Use `xsd.ReadSchemaFromFile` to parse a single XSD file into a `*Schema` object without resolving cross-references or loading imports. This function is suitable for quick schema inspection in isolation.
```go
package main
import (
"fmt"
"log"
"github.com/gocomply/xsd2go/pkg/xsd"
)
func main() {
schema, err := xsd.ReadSchemaFromFile("schemas/types.xsd")
if err != nil {
log.Fatal(err)
}
fmt.Println("Target namespace:", schema.TargetNamespace)
fmt.Println("Elements:", len(schema.Elements))
fmt.Println("ComplexTypes:", len(schema.ComplexTypes))
fmt.Println("SimpleTypes:", len(schema.SimpleTypes))
// Target namespace: https://simple.example.com/
// Elements: 1
// ComplexTypes: 1
// SimpleTypes: 0
}
```
--------------------------------
### Sanitize Untrusted Content with Bluemonday
Source: https://github.com/gocomply/xsd2go/blob/master/vendor/github.com/russross/blackfriday/v2/README.md
Preserve classes of fenced code blocks when using the bluemonday HTML sanitizer by configuring the policy to allow specific attributes on code elements.
```go
p := bluemonday.UGCPolicy()
p.AllowAttrs("class").Matching(regexp.MustCompile("^language-[a-zA-Z0-9]+$")).OnElements("code")
html := p.SanitizeBytes(unsafe)
```
--------------------------------
### xsd.NewWorkspace — Parse XSD schema(s) into an in-memory workspace
Source: https://context7.com/gocomply/xsd2go/llms.txt
Creates a `Workspace` that holds every parsed `Schema` (including transitive imports). This function is used internally by `xsd2go.Convert` but is also available for programmatic schema inspection.
```APIDOC
## xsd.NewWorkspace
### Description
Parses a root XSD file and all its dependencies into an in-memory workspace.
### Method Signature
`func NewWorkspace(goModulePathPrefix string, rootXsdPath string, xmlnsOverrides []string) (*Workspace, error)`
### Parameters
- **goModulePathPrefix** (string) - Required - The Go module path prefix used for resolving relative imports within the workspace.
- **rootXsdPath** (string) - Required - The path to the root XSD file to parse.
- **xmlnsOverrides** ([]string) - Optional - A slice of strings for overriding XML namespaces with custom Go package names (e.g., `"http://example.com/ns=my_ns"`).
### Returns
- **`*Workspace`** - An object containing all parsed schemas and their relationships.
- **`error`** - An error if parsing fails.
### Request Example
```go
package main
import (
"fmt"
"log"
"github.com/gocomply/xsd2go/pkg/xsd"
)
func main() {
ws, err := xsd.NewWorkspace(
"github.com/myorg/myapp/pkg/models",
"schemas/my-schema.xsd",
[]string{
"http://example.com/ns=my_ns",
},
)
if err != nil {
log.Fatal(err)
}
for path, schema := range ws.Cache {
fmt.Printf("Schema: %s namespace: %s package: %s empty: %v\n",
path, schema.TargetNamespace, schema.GoPackageName(), schema.Empty())
}
}
```
```
--------------------------------
### Generated Go Code for SimpleType Enumerations
Source: https://context7.com/gocomply/xsd2go/llms.txt
Go code representing XSD simpleType enumerations as typed string constants. Each constant corresponds to a value defined in the XSD.
```go
// Generated output
type SimpleDatatypeEnumeration string
const (
SimpleDatatypeEnumerationBinary SimpleDatatypeEnumeration = "binary"
SimpleDatatypeEnumerationBoolean SimpleDatatypeEnumeration = "boolean"
SimpleDatatypeEnumerationFloat SimpleDatatypeEnumeration = "float"
SimpleDatatypeEnumerationString SimpleDatatypeEnumeration = "string"
)
```
--------------------------------
### xsd.ReadSchemaFromFile — Parse a single XSD file
Source: https://context7.com/gocomply/xsd2go/llms.txt
Reads and decodes a single XSD file into a `*Schema` object without resolving cross-references or loading imports. This is useful for quick inspection of a schema in isolation.
```APIDOC
## xsd.ReadSchemaFromFile
### Description
Parses a single XSD file into a `*Schema` object.
### Method Signature
`func ReadSchemaFromFile(filePath string) (*Schema, error)`
### Parameters
- **filePath** (string) - Required - The path to the XSD file to read.
### Returns
- **`*Schema`** - A pointer to the parsed Schema object.
- **`error`** - An error if reading or parsing fails.
### Request Example
```go
package main
import (
"fmt"
"log"
"github.com/gocomply/xsd2go/pkg/xsd"
)
func main() {
schema, err := xsd.ReadSchemaFromFile("schemas/types.xsd")
if err != nil {
log.Fatal(err)
}
fmt.Println("Target namespace:", schema.TargetNamespace)
fmt.Println("Elements:", len(schema.Elements))
fmt.Println("ComplexTypes:", len(schema.ComplexTypes))
fmt.Println("SimpleTypes:", len(schema.SimpleTypes))
}
```
```
--------------------------------
### Parse XMLNS Override Strings with xsd.ParseXmlnsOverrides
Source: https://context7.com/gocomply/xsd2go/llms.txt
Converts raw XMLNS override strings into an internal map. Returns an error if any string is not in the expected key=value format.
```go
package main
import (
"fmt"
"log"
"github.com/gocomply/xsd2go/pkg/xsd"
)
func main() {
overrides, err := xsd.ParseXmlnsOverrides([]string{
"http://www.w3.org/2000/09/xmldsig#=xml_signatures",
"http://cpe.mitre.org/language/2.0=cpe_language",
})
if err != nil {
log.Fatal(err) // e.g. "invalid xmlns override: 'bad-string' expecting exactly one '='"
}
fmt.Printf("parsed %d override(s)\n", len(overrides))
// parsed 2 override(s)
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.