Skip to content

xmlquery

450 2 18 MIT
v1.4.2 (7 Oct 2024) Feb 08 2019 58.1 thousand (month)

xmlquery is a Go library that allows you to parse and extract data from XML documents using XPath expressions. It provides a simple and intuitive API for traversing and querying the XML tree structure, and it is built on top of the popular Goquery library.

Note: for parsing HTML sister library htmlquery should be used instead.

Example Use


package main

import (
  "fmt"
  "log"

  "github.com/antchfx/xmlquery"
)

func main() {
  // Parse the XML string
  doc, err := xmlquery.Parse([]byte(`
    <root>
      <person>
        <name>John Doe</name>
        <age>30</age>
        <address>
          <street>Main St</street>
          <city>Anytown</city>
          <state>CA</state>
          <zip>12345</zip>
        </address>
        <phone>555-555-5555</phone>
        <phone>555-555-5556</phone>
      </person>
    </root>
  `))
  if err != nil {
    log.Fatal(err)
  }

  // Extract the name
  name := xmlquery.FindOne(doc, "//person/name")
  fmt.Println(name.InnerText())  // "John Doe"

  // Extract the city
  city := xmlquery.FindOne(doc, "//person/address/city")
  fmt.Println(city.InnerText())  // "Anytown"

  // Extract all phone numbers
  phones := xmlquery.Find(doc, "//person/phone")
  for _, phone := range phones {
    fmt.Println(phone.InnerText())
  }
  // "555-555-5555"
  // "555-555-5556"
}

Alternatives / Similar


mxj
624 per (1 year, 4 months ago) Feb 09 2017 compare

Other Languages

Was this page helpful?