示例#1
0
//This function creates variations on tokens without regards as to positions in the file.
func getTokenVariations(t xml.Token) []xml.Token {
	var result []xml.Token = make([]xml.Token, 0)
	switch t := t.(type) {
	case xml.CharData:
		{
			//If the token is a number try some random number
			if _, err := strconv.Atoi(string(t)); err == nil {
				result = append(result, xml.CharData(randInt(rand.Intn(15))))
			}

			result = append(result, xml.CharData(randString(rand.Intn(100))))
			return result
		}
	case xml.StartElement:
		{
			for k := range t.Attr {
				if _, err := strconv.Atoi(string(t.Attr[k].Value)); err == nil {
					start := xml.CopyToken(t).(xml.StartElement)
					start.Attr[k].Value = string(randInt(rand.Intn(15)))
					result = append(result, start)
				}
				start := xml.CopyToken(t).(xml.StartElement)
				start.Attr[k].Value = string(randString(rand.Intn(100)))
				result = append(result, start)
			}
			return result
		}

	default:
		{
			return make([]xml.Token, 0) // No variations on non char tokens yet
		}
	}
}
示例#2
0
func swCustomized() {
	//println("\nswCustomized")
	d := xml.NewDecoder(strings.NewReader(flatxml))
	e := xml.NewEncoder(os.Stdout)

	nesting := -1
	for {
		t, err := d.Token()
		if err == io.EOF {
			e.Flush()
			return
		}
		if err != nil {
			log.Fatal(err)
		}
		if _, ok := t.(xml.StartElement); ok {
			nesting++
		}
		if nesting > 0 {
			e.EncodeToken(xml.CharData(bytes.Repeat([]byte("  "), nesting)))
		}
		e.EncodeToken(t)
		e.EncodeToken(xml.CharData([]byte{'\n'}))
		if _, ok := t.(xml.EndElement); ok {
			nesting--
		}
		e.Flush()
	}
}
示例#3
0
文件: xmlout.go 项目: speedata/ltxdoc
func marshalDescription(eltname string, e *xml.Encoder, desc map[string]template.HTML) error {
	var err error
	for lang, text := range desc {
		startElt := xml.StartElement{Name: xml.Name{Local: eltname}}

		startElt.Attr = []xml.Attr{
			xml.Attr{Name: xml.Name{Local: "lang"}, Value: lang},
		}

		err = e.EncodeToken(startElt)
		if err != nil {
			return err
		}

		err = e.EncodeToken(xml.CharData(string(text)))
		if err != nil {
			return err
		}

		err = e.EncodeToken(xml.EndElement{Name: startElt.Name})
		if err != nil {
			return err
		}

	}
	return nil
}
示例#4
0
// StructToXML writes an XMLNode to a xml.Encoder as tokens.
func StructToXML(e *xml.Encoder, node *XMLNode, sorted bool) error {
	e.EncodeToken(xml.StartElement{Name: node.Name, Attr: node.Attr})

	if node.Text != "" {
		e.EncodeToken(xml.CharData([]byte(node.Text)))
	} else if sorted {
		sortedNames := []string{}
		for k := range node.Children {
			sortedNames = append(sortedNames, k)
		}
		sort.Strings(sortedNames)

		for _, k := range sortedNames {
			for _, v := range node.Children[k] {
				StructToXML(e, v, sorted)
			}
		}
	} else {
		for _, c := range node.Children {
			for _, v := range c {
				StructToXML(e, v, sorted)
			}
		}
	}

	e.EncodeToken(xml.EndElement{Name: node.Name})
	return e.Flush()
}
示例#5
0
// TrimSpace is a transformer function that replaces CDATA with blank
// characters with empty strings
func TrimSpace(parents *NodeList, in xml.Token) []xml.Token {
	switch t := in.(type) {
	case xml.CharData:
		return []xml.Token{xml.CharData(bytes.TrimSpace(t))}
	}
	return []xml.Token{in}
}
示例#6
0
// MarshalXML ensures addresses marshal to nil if empty without the need
// to use pointers.
func (a Address) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	if a.Address == "" && a.Address2 == "" && a.City == "" && a.State == "" && a.Zip == "" && a.Country == "" && a.Phone == "" {
		return nil
	}

	e.EncodeToken(xml.StartElement{Name: xml.Name{Local: "address"}})
	if a.Address != "" {
		s := xml.StartElement{Name: xml.Name{Local: "address1"}}
		e.EncodeToken(s)
		e.EncodeToken(xml.CharData([]byte(a.Address)))
		e.EncodeToken(xml.EndElement{Name: s.Name})
	}

	if a.Address2 != "" {
		s := xml.StartElement{Name: xml.Name{Local: "address2"}}
		e.EncodeToken(s)
		e.EncodeToken(xml.CharData([]byte(a.Address2)))
		e.EncodeToken(xml.EndElement{Name: s.Name})
	}

	if a.City != "" {
		s := xml.StartElement{Name: xml.Name{Local: "city"}}
		e.EncodeToken(s)
		e.EncodeToken(xml.CharData([]byte(a.City)))
		e.EncodeToken(xml.EndElement{Name: s.Name})
	}

	if a.State != "" {
		s := xml.StartElement{Name: xml.Name{Local: "state"}}
		e.EncodeToken(s)
		e.EncodeToken(xml.CharData([]byte(a.State)))
		e.EncodeToken(xml.EndElement{Name: s.Name})
	}

	if a.Zip != "" {
		s := xml.StartElement{Name: xml.Name{Local: "zip"}}
		e.EncodeToken(s)
		e.EncodeToken(xml.CharData([]byte(a.Zip)))
		e.EncodeToken(xml.EndElement{Name: s.Name})
	}

	if a.Country != "" {
		s := xml.StartElement{Name: xml.Name{Local: "country"}}
		e.EncodeToken(s)
		e.EncodeToken(xml.CharData([]byte(a.Country)))
		e.EncodeToken(xml.EndElement{Name: s.Name})
	}

	if a.Phone != "" {
		s := xml.StartElement{Name: xml.Name{Local: "phone"}}
		e.EncodeToken(s)
		e.EncodeToken(xml.CharData([]byte(a.Phone)))
		e.EncodeToken(xml.EndElement{Name: s.Name})
	}

	e.EncodeToken(xml.EndElement{Name: xml.Name{Local: "address"}})

	return nil
}
示例#7
0
// parseXMLtoTOML parses XML to TOML (in a slightly brain dead way).
func parseXMLtoTOML(input []byte) {
	parser := xml.NewDecoder(bytes.NewReader(input))
	keywords := []string{}
	name := ""
	fmt.Println("% # Quick 'n dirty translated by mmark")
	for {
		token, err := parser.Token()
		if err != nil {
			break
		}
		switch t := token.(type) {
		case xml.StartElement:
			elmt := xml.StartElement(t)
			name = elmt.Name.Local
			switch name {
			case "author":
				fmt.Println("%\n% [[author]]")
				outAttr(elmt.Attr)
			case "rfc":
				fallthrough
			case "title":
				outAttr(elmt.Attr)
			case "address":
				fmt.Println("% [author.address]")
			case "postal":
				fmt.Println("% [author.address.postal]")
			case "date":
				outDate(elmt.Attr)
			}
		case xml.CharData:
			if name == "" {
				continue
			}
			data := xml.CharData(t)
			data = bytes.TrimSpace(data)
			if len(data) == 0 {
				continue
			}
			if name == "keyword" {
				keywords = append(keywords, "\""+string(data)+"\"")
				continue
			}
			outString(name, string(data))
		case xml.EndElement:
			name = ""
		case xml.Comment:
			// don't care
		case xml.ProcInst:
			// don't care
		case xml.Directive:
			// don't care
		default:
		}
	}
	outArray("keyword", keywords)
}
示例#8
0
func parseProfileXML(profileName string, text string) Profile {
	p := new(Profile)
	p.name = profileName
	p.fieldPermissions = map[string]FLS{}
	p.objectPermissions = map[string]OLS{}
	var currentElement XLS

	r := strings.NewReader(text)
	parser := xml.NewDecoder(r)
	depth := 0

	eltType := ""
	propertyName := ""

	for {

		token, err := parser.Token()
		if err != nil {
			break
		}
		switch t := token.(type) {
		case xml.StartElement:
			elmt := xml.StartElement(t)
			name := elmt.Name.Local
			if depth == 1 {
				eltType = name
				if eltType == "objectPermissions" {
					currentElement = new(OLS)
				} else if eltType == "fieldPermissions" {
					currentElement = new(FLS)
				} else {
					currentElement = nil
				}
			}
			if depth == 2 {
				propertyName = name
			}
			depth++
		case xml.EndElement:
			if depth == 2 && currentElement != nil {
				currentElement.addToProfile(*p)
			}
			depth--
		case xml.CharData:
			bytes := xml.CharData(t)
			if currentElement != nil && depth == 3 {
				currentElement.addProperty(propertyName, string(bytes))
			}
		default:
		}
	}

	//	fmt.Println(p)

	return *p
}
示例#9
0
func (d *XmlDataOutput) DumpString(field, value string) {
	if d.lastError != nil {
		return
	}
	d.lastError = d.writeTokens([]xml.Token{
		xml.StartElement{Name: xml.Name{Local: field}},
		xml.CharData(value),
		xml.EndElement{Name: xml.Name{Local: field}},
	})
}
示例#10
0
func getChildElements(commands *commandsxml.CommandsXML, enc *xml.Encoder, children []byte, lang string) {
	if len(children) == 0 {
		enc.EncodeToken(emptyElement.Copy())
		enc.EncodeToken(emptyElement.End())
	}
	buf := bytes.NewBuffer(children)
	dec := xml.NewDecoder(buf)
	for {
		tok, err := dec.Token()
		if err != nil {
			return
		}
		switch v := tok.(type) {
		case xml.StartElement:
			switch v.Name.Local {
			case "cmd":
				ref := refElement.Copy()
				for _, attr := range v.Attr {
					if attr.Name.Local == "name" {
						ref.Attr = []xml.Attr{{Name: xml.Name{Local: "name"}, Value: "e_" + attr.Value}}
					}
				}
				enc.EncodeToken(ref)
			case "description":
			case "choice":
				enc.EncodeToken(choiceElement.Copy())
				for _, attribute := range v.Attr {
					if attribute.Name.Local == lang {
						enc.EncodeToken(valueElement.Copy())
						enc.EncodeToken(xml.CharData(attribute.Value))
						enc.EncodeToken(valueElement.End())
					}
				}
			case "reference":
				for _, attr := range v.Attr {
					if attr.Name.Local == "name" {
						getChildElements(commands, enc, commands.GetDefine(attr.Value), lang)
					}
				}
			default:
				enc.EncodeToken(v.Copy())
			}

		case xml.EndElement:
			switch v.Name.Local {
			case "cmd":
				enc.EncodeToken(refElement.End())
			case "choice":
				enc.EncodeToken(choiceElement.End())
			default:
				enc.EncodeToken(v)
			}
		}
	}
}
示例#11
0
func (d *XmlDataOutput) DumpDouble(field string, value float64) {
	if d.lastError != nil {
		return
	}
	if err := d.writeTokens([]xml.Token{
		xml.StartElement{Name: xml.Name{Local: field}},
		xml.CharData(strconv.FormatFloat(value, 'e', 10, 64)),
		xml.EndElement{Name: xml.Name{Local: field}},
	}); err != nil {
		d.lastError = errors.Wrap(err, 0)
	}
}
示例#12
0
func (d *XmlDataOutput) DumpUnsignedLong(field string, value uint64) {
	if d.lastError != nil {
		return
	}
	if err := d.writeTokens([]xml.Token{
		xml.StartElement{Name: xml.Name{Local: field}},
		xml.CharData(strconv.FormatUint(value, 10)),
		xml.EndElement{Name: xml.Name{Local: field}},
	}); err != nil {
		d.lastError = errors.Wrap(err, 0)
	}
}
示例#13
0
文件: xml.go 项目: katydid/katydid
func getCharData(p parser.Interface) xml.CharData {
	i, err := p.Int()
	if err == nil {
		return xml.CharData([]byte(strconv.FormatInt(i, 10)))
	}
	u, err := p.Uint()
	if err == nil {
		return xml.CharData([]byte(strconv.FormatUint(u, 10)))
	}
	d, err := p.Double()
	if err == nil {
		return xml.CharData([]byte(strconv.FormatFloat(d, 'e', -1, 64)))
	}
	b, err := p.Bool()
	if err == nil {
		return xml.CharData([]byte(strconv.FormatBool(b)))
	}
	s, err := p.String()
	if err == nil {
		return xml.CharData([]byte(s))
	}
	v, err := p.Bytes()
	if err == nil {
		return xml.CharData([]byte(base64.StdEncoding.EncodeToString(v)))
	}
	return nil
}
示例#14
0
func (d *XmlDataOutput) DumpTime(field string, value time.Time) {
	if d.lastError != nil {
		return
	}
	if err := d.writeTokens([]xml.Token{
		xml.StartElement{Name: xml.Name{Local: field}},
		xml.CharData(strconv.FormatInt(value.Unix(), 10)),
		xml.EndElement{Name: xml.Name{Local: field}},
		xml.Comment(value.String()),
	}); err != nil {
		d.lastError = errors.Wrap(err, 0)
	}
}
示例#15
0
文件: ParseXML.go 项目: sjtlqy/Go
func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: ", os.Args[0], "file")
		os.Exit(1)
	}
	file := os.Args[1]
	bytes, err := ioutil.ReadFile(file)
	checkError(err)
	r := strings.NewReader(string(bytes))

	parser := xml.NewDecoder(r)
	depth := 0
	for {
		token, err := parser.Token()
		if err != nil {
			break
		}
		switch t := token.(type) {
		case xml.StartElement:
			elmt := xml.StartElement(t)
			name := elmt.Name.Local
			printElmt(name, depth)
			depth++
		case xml.EndElement:
			depth--
			elmt := xml.EndElement(t)
			name := elmt.Name.Local
			printElmt(name, depth)
		case xml.CharData:
			bytes :=
				xml.CharData(t)
			printElmt("\""+string([]byte(bytes))+"\"",
				depth)
		case
			xml.Comment:
			printElmt("Comment",
				depth)
		case
			xml.ProcInst:
			printElmt("ProcInst",
				depth)
		case
			xml.Directive:
			printElmt("Directive",
				depth)
		default:
			fmt.Println("Unknown")
		}
	}
}
示例#16
0
文件: main.go 项目: brydavis/xql
func Elementize(dec *xml.Decoder) (data string) {
	var parentNode string
	var attrs bool
	for {
		token, err := dec.Token()
		if err != nil {
			break
		}

		switch t := token.(type) {
		case xml.StartElement:
			parentNode = t.Name.Local
			data += fmt.Sprintf("<%s>", t.Name.Local)
			if len(t.Attr) > 0 {
				attrs = true
				// data += "<attr>"
				for _, v := range t.Attr {
					data += fmt.Sprintf("<%s>%s</%s>", v.Name.Local, v.Value, v.Name.Local)
				}
				// data += "</attr>"
			} else {
				attrs = false
			}

		case xml.EndElement:
			data += fmt.Sprintf("</%s>", t.Name.Local)

		case xml.CharData:
			val := strings.Replace(strings.TrimSpace(string(xml.CharData(t))), "\n", "", -1)
			if val != "" {
				// data += fmt.Sprintf("<value>%s</value>", val)
				if attrs {
					data += fmt.Sprintf("<%s>%s</%s>", parentNode, val, parentNode)

				} else {
					data += fmt.Sprintf("%s", val)

				}
			}

		case xml.ProcInst:
			// fmt.Printf("not supported: %v\n", t)

		default:
			fmt.Printf("type not supported: %v\n", t)
		}
	}
	return
}
示例#17
0
// NewCompactSearchResult _always_ close this
func NewCompactSearchResult(body io.ReadCloser) (*CompactSearchResult, error) {
	parser := DefaultXMLDecoder(body, false)
	result := &CompactSearchResult{
		body:   body,
		parser: parser,
	}
	// extract the basic content before delving into the data
	for {
		token, err := parser.Token()
		if err != nil {
			return result, err
		}
		switch t := token.(type) {
		case xml.StartElement:
			// clear any accumulated data
			result.buf.Reset()
			switch t.Name.Local {
			case XMLElemRETS, XMLElemRETSStatus:
				resp, er := ResponseTag(t).Parse()
				if er != nil {
					return result, er
				}
				result.Response = *resp
			case "COUNT":
				result.Count, err = countTag(t).Parse()
				if err != nil {
					return result, err
				}
			case "DELIMITER":
				result.Delimiter, err = DelimiterTag(t).Parse()
				if err != nil {
					return result, err
				}
			}
		case xml.EndElement:
			switch t.Name.Local {
			case "COLUMNS":
				result.Columns = CompactRow(result.buf.String()).Parse(result.Delimiter)
				return result, nil
			case XMLElemRETS, XMLElemRETSStatus:
				// if there is only a RETS tag.. just exit
				return result, nil
			}
		case xml.CharData:
			bytes := xml.CharData(t)
			result.buf.Write(bytes)
		}
	}
}
示例#18
0
func format(encoder *xml.Encoder, decoder *xml.Decoder, d core.Dict) (nilMap map[string]int) {

	// nilArr  := make([]string, 10)
	// nilCnt  := 0
	nilMap = make(map[string]int)
	dict := d.GetData()

	focus := false
	for tk, e := decoder.Token(); e == nil; tk, e = decoder.Token() {

	S:
		switch tmp := tk.(type) {

		case xml.StartElement:
			focus = tmp.Name.Local == "string"
			// fmt.Printf("token show : %v\n", tmp.Name.Space)

		// case xml.EndElement:
		case xml.CharData:
			if !focus {
				break S
			}

			content := string([]byte(tmp))
			if strings.IndexFunc(content, matchF) == -1 {
				break S
			}

			if value, ok := dict[content]; ok {

				tk = xml.CharData([]byte(value.ToString()))
			} else {

				if _, ok := nilMap[content]; !ok {

					nilMap[content] = 0
				}
			}

		default:
		}
		encoder.EncodeToken(tk)
	}

	return
}
示例#19
0
文件: decode.go 项目: postfix/ivega
func set(n *node, s string) (string, error) {
	if n == nil {
		return s, nil
	}

	switch n.typ {
	case BARE:
		return set(n.pre, s)
	case BASE64:
		return set(n.pre, base64.StdEncoding.EncodeToString([]byte(s)))
	case BASE64_URL:
		return set(n.pre, base64.URLEncoding.EncodeToString([]byte(s)))
	case URL_ENCODE:
		return set(n.pre, url.QueryEscape(s))
	case JSONMAP:
		obj, _ := n.obj.(*jsonMap)
		save := obj.m[obj.k]
		obj.m[obj.k] = s
		j, err := json.Marshal(obj.org)
		obj.m[obj.k] = save
		if err != nil {
			return "", err
		}
		return set(n.pre, string(j))
	case JSONARRAY:
		obj, _ := n.obj.(*jsonArray)
		save := obj.a[obj.i]
		obj.a[obj.i] = s
		j, err := json.Marshal(obj.org)
		obj.a[obj.i] = save
		if err != nil {
			return "", err
		}
		return set(n.pre, string(j))
	case XMLOBJ:
		obj, _ := n.obj.(*xmlObj)
		save := obj.xt[obj.index].token
		obj.xt[obj.index].token = xml.CharData(s)
		x := obj.marshal()
		obj.xt[obj.index].token = save
		return set(n.pre, string(x))
	default:
		panic("Decode type invalid!")
	}
}
示例#20
0
// Decode reads the next JSON-encoded value from its
// input and stores it in the value pointed to by v.
func (dec *Decoder) Decode(root *Node) error {
	xmlDec := xml.NewDecoder(dec.r)

	// Create first element from the root node
	elem := &element{
		parent: nil,
		n:      root,
	}

	for {
		t, _ := xmlDec.Token()
		if t == nil {
			break
		}

		switch se := t.(type) {
		case xml.StartElement:
			// Build new a new current element and link it to its parent
			elem = &element{
				parent: elem,
				n:      &Node{},
				label:  se.Name.Local,
			}

			// Extract attributes as children
			for _, a := range se.Attr {
				elem.n.AddChild(dec.attrPrefix+a.Name.Local, &Node{Data: a.Value})
			}
		case xml.CharData:
			// Extract XML data (if any)
			elem.n.Data = string(xml.CharData(se))
		case xml.EndElement:
			// And add it to its parent list
			if elem.parent != nil {
				elem.parent.n.AddChild(elem.label, elem.n)
			}

			// Then change the current element to its parent
			elem = elem.parent
		}
	}

	return nil
}
示例#21
0
func parseCustomObjectXML(objectName string, text string) CustomObject {
	obj := CustomObject{objectName: objectName, nbFields: 0, fieldNames: make([]string, 900, 900)}
	r := strings.NewReader(text)
	parser := xml.NewDecoder(r)
	depth := 0
	var firstLevel, secondLevel string

	for {

		token, err := parser.Token()
		if err != nil {
			break
		}
		switch t := token.(type) {
		case xml.StartElement:
			elmt := xml.StartElement(t)
			name := elmt.Name.Local
			if depth == 1 {
				firstLevel = name
			} else if depth == 2 {
				secondLevel = name
			}
			depth++
		case xml.EndElement:
			if depth == 3 {
				secondLevel = ""
			} else if depth == 2 {
				firstLevel = ""
			}
			depth--
		case xml.CharData:
			bytes := xml.CharData(t)
			if depth == 3 && firstLevel == "fields" && secondLevel == "fullName" {
				obj.addField(string(bytes))
			}
		default:
		}
	}

	//	fmt.Println(obj)
	return obj
}
示例#22
0
func (e *XMLFormat) WriteRow(values map[string]interface{}) error {
	row := xml.StartElement{Name: xml.Name{"", "row"}}
	tokens := []xml.Token{row}
	for key, value := range values {
		var charData xml.CharData

		t := xml.StartElement{Name: xml.Name{"", key}}

		switch value := (value).(type) {
		case string:
			charData = xml.CharData(value)
		case []byte:
			charData = xml.CharData(string(value))
		case int64:
			charData = xml.CharData(fmt.Sprintf("%d", value))
		case float64:
			charData = xml.CharData(strconv.FormatFloat(value, 'f', -1, 64))
		case time.Time:
			charData = xml.CharData(value.Format(time.RFC3339))
		case bool:
			if value == true {
				charData = xml.CharData("true")
			} else {
				charData = xml.CharData("false")
			}
		}
		tokens = append(tokens, t, charData, t.End())
	}
	tokens = append(tokens, row.End())

	for _, t := range tokens {
		err := e.encoder.EncodeToken(t)
		if err != nil {
			return err
		}
	}

	err := e.encoder.Flush()
	if err != nil {
		return err
	}

	return nil
}
示例#23
0
文件: entity.go 项目: kpmy/xippo
func (x *domm) MarshalXML(e *xml.Encoder, start xml.StartElement) (err error) {
	start.Name.Local = x.model.Name()
	for k, v := range x.model.AttrAsMap() {
		start.Attr = append(start.Attr, xml.Attr{Name: xml.Name{Local: k}, Value: v})
	}
	e.EncodeToken(start)
	for _, _l := range x.model.Children() {
		switch l := _l.(type) {
		case dom.Element:
			child := &domm{}
			child.model = l
			e.Encode(child)
		case dom.Text:
			e.EncodeToken(xml.CharData(l.Data()))
		default:
			halt.As(100, reflect.TypeOf(l))
		}
	}
	e.EncodeToken(start.End())
	return
}
示例#24
0
// MarshalXML is a custom XML marshaler for InstanceMetadata.
func (i InstanceMetadata) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	tokens := []xml.Token{start}

	if i.parsed != nil {
		for key, value := range i.parsed {
			t := xml.StartElement{Name: xml.Name{"", key}}
			tokens = append(tokens, t, xml.CharData(value.(string)), xml.EndElement{t.Name})
		}
	}
	tokens = append(tokens, xml.EndElement{start.Name})

	for _, t := range tokens {
		err := e.EncodeToken(t)
		if err != nil {
			return err
		}
	}

	// flush to ensure tokens are written
	return e.Flush()
}
示例#25
0
文件: ot_test_stuff.go 项目: kpmy/ot
func renderHtml(o otm.Object, log *testing.T) {
	buf := bytes.NewBufferString("<!DOCTYPE HTML>")
	e := xml.NewEncoder(buf)
	var obj func(otm.Object)
	obj = func(o otm.Object) {
		clazz := o.InstanceOf().Qualident()
		if clazz.Template == "html" {
			start := xml.StartElement{}
			start.Name.Local = clazz.Class
			if id := o.Qualident().Identifier; id != "" {
				attr := xml.Attr{}
				attr.Name.Local = "id"
				attr.Value = id
				start.Attr = append(start.Attr, attr)
			}
			e.EncodeToken(start)
			for _x := range o.Children() {
				switch x := _x.(type) {
				case otm.Object:
					obj(x)
				case string:
					e.EncodeToken(xml.CharData([]byte(x)))
				default:
					halt.As(100, reflect.TypeOf(x))
				}
			}
			e.EncodeToken(start.End())
		}
	}

	for x := range o.ChildrenObjects() {
		if x.InstanceOf().Qualident().Template == "html" && x.InstanceOf().Qualident().Class == "html" {
			obj(x)
		}
	}
	e.Flush()
	log.Log(buf.String())
}
示例#26
0
//UnmarshalXML for Match struct in a special way to handle highlighting matching text
func (m *Match) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	for i := range start.Attr {
		attr := start.Attr[i]
		if attr.Name.Local == "path" {
			m.Path = attr.Value
			break
		}
	}
	for {
		if token, err := d.Token(); (err == nil) && (token != nil) {
			switch t := token.(type) {
			case xml.StartElement:
				var content string
				e := xml.StartElement(t)
				d.DecodeElement(&content, &e)
				text := Text{
					Text:            content,
					HighlightedText: e.Name.Space == searchNamespace && e.Name.Local == "highlight",
				}
				m.Text = append(m.Text, text)
			case xml.EndElement:
				e := xml.EndElement(t)
				if e.Name.Space == searchNamespace && e.Name.Local == "match" {
					return nil
				}
			case xml.CharData:
				b := xml.CharData(t)
				text := Text{
					Text:            string([]byte(b)),
					HighlightedText: false,
				}
				m.Text = append(m.Text, text)
			}
		} else {
			return err
		}
	}
}
示例#27
0
func encodeInterfaceType(name string, enc *xml.Encoder, v interface{}) (del bool, newVal interface{}, err error) {
	val := reflect.ValueOf(v)
	if val.Kind() == reflect.Slice {
		if val.Len() == 0 {
			del = true
			return
		}

		var d bool
		if d, newVal, err = encodeInterfaceType(name, enc, val.Index(0).Interface()); err != nil {
			return
		} else if d {
			newVal = val.Slice(1, val.Len()).Interface()
		}

		if reflect.ValueOf(newVal).Len() == 0 {
			del = true
		}
		return
	}

	for _, m := range mappings {
		for _, n := range m.xsdSchema {
			if n == name {
				for _, t := range m.kinds {
					if t == val.Kind() {
						del = true
						err = enc.EncodeToken(xml.CharData(fmt.Sprintf(m.format, v)))
						return
					}
				}
			}
		}
	}

	err = fmt.Errorf("no mapping found for xsd base type %s and kind %s", name, val.Kind())
	return
}
func (s *MetaData) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
	var attributes []xml.Attr = make([]xml.Attr, 0)
	if s.Class != "" {
		attributes = append(attributes, xml.Attr{
			Name: xml.Name{
				Local: "class",
			},
			Value: s.Class,
		})
	}
	start.Attr = attributes
	tokens := []xml.Token{start}

	for key, value := range s.Map {
		t := xml.StartElement{Name: xml.Name{"", key}}
		tokens = append(tokens, t, xml.CharData(value), xml.EndElement{t.Name})
	}

	tokens = append(tokens, xml.EndElement{
		Name: start.Name,
	})

	for _, t := range tokens {
		err := e.EncodeToken(t)
		if err != nil {
			return err
		}
	}

	// flush to ensure tokens are written
	err := e.Flush()
	if err != nil {
		return err
	}

	return nil
}
示例#29
0
// ForEach returns MaxRows and any error that 'each' wont handle
func (c *CompactSearchResult) ForEach(each EachRow) (bool, error) {
	defer c.body.Close()
	maxRows := false
	for {
		token, err := c.parser.Token()
		if err != nil {
			// dont catch io.EOF here since a clean read should never see it
			if err = each(nil, err); err != nil {
				return maxRows, err
			}
			continue
		}
		switch t := token.(type) {
		case xml.StartElement:
			// clear any accumulated data
			c.buf.Reset()
			// check tags
			switch t.Name.Local {
			case "MAXROWS":
				maxRows = true
			}
		case xml.EndElement:
			switch t.Name.Local {
			case "DATA":
				err := each(CompactRow(c.buf.String()).Parse(c.Delimiter), nil)
				if err != nil {
					return maxRows, err
				}
			case XMLElemRETS, XMLElemRETSStatus:
				return maxRows, nil
			}
		case xml.CharData:
			bytes := xml.CharData(t)
			c.buf.Write(bytes)
		}
	}
}
示例#30
0
// Close completes the marshalling of the multistatus response. It returns
// an error if the multistatus response could not be completed. If both the
// return value and field enc of w are nil, then no multistatus response has
// been written.
func (w *multistatusWriter) close() error {
	if w.enc == nil {
		return nil
	}
	var end []xml.Token
	if w.responseDescription != "" {
		name := xml.Name{Space: "DAV:", Local: "responsedescription"}
		end = append(end,
			xml.StartElement{Name: name},
			xml.CharData(w.responseDescription),
			xml.EndElement{Name: name},
		)
	}
	end = append(end, xml.EndElement{
		Name: xml.Name{Space: "DAV:", Local: "multistatus"},
	})
	for _, t := range end {
		err := w.enc.EncodeToken(t)
		if err != nil {
			return err
		}
	}
	return w.enc.Flush()
}