Home > OS >  Parsing XML of the different tag under same parent tags in Go
Parsing XML of the different tag under same parent tags in Go

Time:05-16

I am new to Go, and I am trying to parse an XML file. I don't know how to convert the xml like below into a struct. My XML file:

<profile>
    <subsystem xmlns="urn:jboss:domain:logging:1.1">
            <root-logger>
                <level name="INFO"/>
                <handlers>
                    <handler name="CONSOLE"/>
                    <handler name="FILE"/>
                </handlers>
            </root-logger>
    </subsystem>
    <subsystem xmlns="urn:jboss:domain:configadmin:1.0"/>
    <subsystem xmlns="urn:jboss:domain:deployment-scanner:1.1">
            <deployment-scanner path="deployments" relative-to="jboss.server.base.dir" scan-interval="5000"/>
    </subsystem>
 </profile>     

CodePudding user response:

My problem can be easily solved by using slices. The following code is the corresponding structure.

type Level struct {
    Name string `xml:"name,attr"`
}
type Handler struct {
    Name string `xml:"name,attr"`
}
type Handlers struct {
    Handler []Handler `xml:"handler"`
}

type RootLogger struct {
    Level   Level    `xml:"level"`
    Handler Handlers `xml:"handlers"`
}

type DeploymentScanner struct {
    Path         string `xml:"path,attr"`
    RelativeTo   string `xml:"relative-to,attr"`
    ScanInterval string `xml:"scan-interval,attr"`
}

type Subsystem struct {
    XMLName           xml.Name
    RootLogger        []RootLogger        `xml:"root-logger"`
    DeploymentScanner []DeploymentScanner `xml:"deployment-scanner"`
}

type Profile struct {
    Subsystem []Subsystem `xml:"subsystem"`
}

Go Playground

  • Related