go-pkg-xmlx/src/document.go

230 lines
5.6 KiB
Go
Raw Normal View History

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Author: Jim Teeuwen <jimteeuwen@gmail.com>
This package wraps the standard XML library and uses it to build a node tree of
any document you load. This allows you to look up nodes forwards and backwards,
as well as perform search queries (no xpath support yet).
Nodes now simply become collections and don't require you to read them in the
order in which the xml.Parser finds them.
The Document currently implements 2 simple search functions which allow you to
look for specific nodes.
2010-05-06 03:36:48 +00:00
Document.SelectNode(namespace, name string) *Node;
Document.SelectNodes(namespace, name string) []*Node;
2010-05-06 03:36:48 +00:00
SelectNode() returns the first, single node it finds matching the given name
and namespace. SelectNodes() returns a slice containing all the matching nodes.
2010-05-06 03:36:48 +00:00
Note that these search functions can be invoked on individual nodes as well.
This allows you to search only a subset of the entire document.
*/
package xmlx
import "os"
import "io"
import "io/ioutil"
import "path"
import "strings"
import "xml"
import "fmt"
import "http"
type Document struct {
2010-05-06 03:36:48 +00:00
Version string
Encoding string
StandAlone string
SaveDocType bool
Root *Node
Entity map[string]string
Verbose bool
}
func New() *Document {
return &Document{
2010-05-06 03:36:48 +00:00
Version: "1.0",
Encoding: "utf-8",
StandAlone: "yes",
SaveDocType: true,
2010-05-06 03:36:48 +00:00
Entity: make(map[string]string),
Verbose: false,
}
}
// This loads a rather massive table of non-conventional xml escape sequences.
// Needed to make the parser map them to characters properly. It is advised to
// set only those entities needed manually using the document.Entity map, but
// if need be, this method can be called to fill the map with the entire set
// defined on http://www.w3.org/TR/html4/sgml/entities.html
2010-05-06 03:36:48 +00:00
func (this *Document) LoadExtendedEntityMap() { loadNonStandardEntities(&this.Entity) }
func (this *Document) String() string {
2010-05-06 03:36:48 +00:00
s, _ := this.SaveString()
return s
}
func (this *Document) SelectNode(namespace, name string) *Node {
2010-05-06 03:36:48 +00:00
return this.Root.SelectNode(namespace, name)
}
func (this *Document) SelectNodes(namespace, name string) []*Node {
2010-05-06 03:36:48 +00:00
return this.Root.SelectNodes(namespace, name)
}
// *****************************************************************************
// *** Satisfy ILoader interface
// *****************************************************************************
func (this *Document) LoadString(s string) (err os.Error) {
2010-05-06 03:36:48 +00:00
xp := xml.NewParser(strings.NewReader(s))
xp.Entity = this.Entity
2009-11-23 16:50:29 +00:00
2010-05-06 03:36:48 +00:00
this.Root = NewNode(NT_ROOT)
ct := this.Root
var tok xml.Token
for {
if tok, err = xp.Token(); err != nil {
if err == os.EOF {
return nil
}
if this.Verbose {
fmt.Fprintf(os.Stderr, "Xml Error: %s\n", err)
}
return err
}
switch tt := tok.(type) {
case xml.SyntaxError:
return os.NewError(tt.String())
case xml.CharData:
ct.Value = strings.TrimSpace(string(tt))
case xml.Comment:
2010-05-06 03:36:48 +00:00
t := NewNode(NT_COMMENT)
t.Value = strings.TrimSpace(string(tt))
2010-05-06 03:36:48 +00:00
ct.AddChild(t)
case xml.Directive:
2010-05-06 03:36:48 +00:00
t := NewNode(NT_DIRECTIVE)
t.Value = strings.TrimSpace(string(tt))
2010-05-06 03:36:48 +00:00
ct.AddChild(t)
case xml.StartElement:
2010-05-06 03:36:48 +00:00
t := NewNode(NT_ELEMENT)
t.Name = tt.Name
t.Attributes = make([]Attr, len(tt.Attr))
for i, v := range tt.Attr {
2010-05-06 03:36:48 +00:00
t.Attributes[i].Name = v.Name
t.Attributes[i].Value = v.Value
}
2010-05-06 03:36:48 +00:00
ct.AddChild(t)
ct = t
case xml.ProcInst:
if tt.Target == "xml" { // xml doctype
doctype := strings.TrimSpace(string(tt.Inst))
2010-05-06 03:36:48 +00:00
pos := strings.Index(doctype, `standalone="`)
if pos > -1 {
2010-05-06 03:36:48 +00:00
this.StandAlone = doctype[pos+len(`standalone="`) : len(doctype)]
pos = strings.Index(this.StandAlone, `"`)
this.StandAlone = this.StandAlone[0:pos]
}
} else {
2010-05-06 03:36:48 +00:00
t := NewNode(NT_PROCINST)
t.Target = strings.TrimSpace(tt.Target)
t.Value = strings.TrimSpace(string(tt.Inst))
2010-05-06 03:36:48 +00:00
ct.AddChild(t)
}
case xml.EndElement:
if ct = ct.Parent; ct == nil {
return
}
}
}
2010-05-06 03:36:48 +00:00
return
}
func (this *Document) LoadFile(filename string) (err os.Error) {
var data []byte
if data, err = ioutil.ReadFile(path.Clean(filename)); err != nil {
return
}
return this.LoadString(string(data))
}
func (this *Document) LoadUri(uri string) (err os.Error) {
2010-05-06 03:36:48 +00:00
r, _, err := http.Get(uri)
if err != nil {
return
}
2010-05-06 03:36:48 +00:00
defer r.Body.Close()
var b []byte
if b, err = ioutil.ReadAll(r.Body); err != nil {
return
}
err = this.LoadString(string(b))
2010-05-06 03:36:48 +00:00
return
}
func (this *Document) LoadStream(r *io.Reader) (err os.Error) {
2010-05-06 03:36:48 +00:00
content := ""
buff := make([]byte, 256)
for {
2010-05-06 03:36:48 +00:00
_, err := r.Read(buff)
if err != nil {
break
}
2010-05-06 03:36:48 +00:00
content += string(buff)
}
2010-05-06 03:36:48 +00:00
err = this.LoadString(content)
return
}
// *****************************************************************************
// *** Satisfy ISaver interface
// *****************************************************************************
func (this *Document) SaveFile(path string) (err os.Error) {
2010-05-06 03:36:48 +00:00
file, err := os.Open(path, os.O_WRONLY|os.O_CREAT, 0600)
if err != nil {
return
}
2010-05-06 03:36:48 +00:00
defer file.Close()
2010-05-06 03:36:48 +00:00
content, err := this.SaveString()
if err != nil {
return
}
2010-05-06 03:36:48 +00:00
file.Write([]byte(content))
return
}
func (this *Document) SaveString() (s string, err os.Error) {
if this.SaveDocType {
s = fmt.Sprintf(`<?xml version="%s" encoding="%s" standalone="%s"?>`,
this.Version, this.Encoding, this.StandAlone)
}
2010-05-06 03:36:48 +00:00
s += this.Root.String()
return
}
func (this *Document) SaveStream(w *io.Writer) (err os.Error) {
2010-05-06 03:36:48 +00:00
s, err := this.SaveString()
if err != nil {
return
}
2010-05-06 03:36:48 +00:00
w.Write([]byte(s))
return
}