- Notifications
You must be signed in to change notification settings - Fork181
parse and generate XML easily in go
License
beevik/etree
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
The etree package is a lightweight, pure go package that expresses XML inthe form of an element tree. Its design was inspired by the PythonElementTreemodule.
Some of the package's capabilities and features:
- Represents XML documents as trees of elements for easy traversal.
- Imports, serializes, modifies or creates XML documents from scratch.
- Writes and reads XML to/from files, byte slices, strings and io interfaces.
- Performs simple or complex searches with lightweight XPath-like query APIs.
- Auto-indents XML using spaces or tabs for better readability.
- Implemented in pure go; depends only on standard go libraries.
- Built on top of the goencoding/xmlpackage.
The following example creates an XML document from scratch using the etreepackage and outputs its indented contents to stdout.
doc:=etree.NewDocument()doc.CreateProcInst("xml",`version="1.0" encoding="UTF-8"`)doc.CreateProcInst("xml-stylesheet",`type="text/xsl" href="style.xsl"`)people:=doc.CreateElement("People")people.CreateComment("These are all known people")jon:=people.CreateElement("Person")jon.CreateAttr("name","Jon")sally:=people.CreateElement("Person")sally.CreateAttr("name","Sally")doc.Indent(2)doc.WriteTo(os.Stdout)
Output:
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="style.xsl"?><People><!--These are all known people--> <Personname="Jon"/> <Personname="Sally"/></People>
Suppose you have a file on disk calledbookstore.xml
containing thefollowing data:
<bookstorexmlns:p="urn:schemas-books-com:prices"> <bookcategory="COOKING"> <titlelang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <p:price>30.00</p:price> </book> <bookcategory="CHILDREN"> <titlelang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <p:price>29.99</p:price> </book> <bookcategory="WEB"> <titlelang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <p:price>49.99</p:price> </book> <bookcategory="WEB"> <titlelang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <p:price>39.95</p:price> </book></bookstore>
This code reads the file's contents into an etree document.
doc:=etree.NewDocument()iferr:=doc.ReadFromFile("bookstore.xml");err!=nil {panic(err)}
You can also read XML from a string, a byte slice, or anio.Reader
.
This example illustrates several ways to access elements and attributes usingetree selection queries.
root:=doc.SelectElement("bookstore")fmt.Println("ROOT element:",root.Tag)for_,book:=rangeroot.SelectElements("book") {fmt.Println("CHILD element:",book.Tag)iftitle:=book.SelectElement("title");title!=nil {lang:=title.SelectAttrValue("lang","unknown")fmt.Printf(" TITLE: %s (%s)\n",title.Text(),lang) }for_,attr:=rangebook.Attr {fmt.Printf(" ATTR: %s=%s\n",attr.Key,attr.Value) }}
Output:
ROOT element: bookstoreCHILD element: book TITLE: Everyday Italian (en) ATTR: category=COOKINGCHILD element: book TITLE: Harry Potter (en) ATTR: category=CHILDRENCHILD element: book TITLE: XQuery Kick Start (en) ATTR: category=WEBCHILD element: book TITLE: Learning XML (en) ATTR: category=WEB
This example uses etree's path functions to select all book titles that fallinto the category of 'WEB'. The double-slash prefix in the path causes thesearch for book elements to occur recursively; book elements may appear at anylevel of the XML hierarchy.
for_,t:=rangedoc.FindElements("//book[@category='WEB']/title") {fmt.Println("Title:",t.Text())}
Output:
Title: XQuery Kick StartTitle: Learning XML
This example finds the first book element under the root bookstore element andoutputs the tag and text of each of its child elements.
for_,e:=rangedoc.FindElements("./bookstore/book[1]/*") {fmt.Printf("%s: %s\n",e.Tag,e.Text())}
Output:
title: Everyday Italianauthor: Giada De Laurentiisyear: 2005price: 30.00
This example finds all books with a price of 49.99 and outputs their titles.
path:=etree.MustCompilePath("./bookstore/book[p:price='49.99']/title")for_,e:=rangedoc.FindElementsPath(path) {fmt.Println(e.Text())}
Output:
XQuery Kick Start
Note that this example uses the FindElementsPath function, which takes as anargument a pre-compiled path object. Use precompiled paths when you plan tosearch with the same path more than once.
These are just a few examples of the things the etree package can do. See thedocumentation for a completedescription of its capabilities.
This project accepts contributions. Just fork the repo and submit a pullrequest!
About
parse and generate XML easily in go