使用xmlpath.v2 golang获取节点的值

时间:2017-08-21 12:31:35

标签: xml parsing xpath go

我正在使用gopkg.in/xmlpath.v2解析xml文档,我发现了一个问题...我从单个节点获取信息没有问题,或者获取迭代器并循环获取其信息的项目。但是,我被阻止的情况是当我尝试从我正在迭代的同一节点获取信息时。我认为这个例子很有启发性 这是XML:

<Warnings>
    <Warning Type="309" ShortText="Unfulfilled Paid Service 1">Unable to book seat 1</Warning>
    <Warning Type="309" ShortText="Unfulfilled Paid Service 2">Unable to book seat 2</Warning>
    <Warning Type="309" ShortText="Unfulfilled Paid Service 3">Unable to book seat 3</Warning>
</Warnings>

这些是我使用的xpath:

xpath := xPathWarning{
    WarningsBase:       "Warnings/Warning",
    Warning:            "",
    WarningAttr:        "@ShortText",
}

这就是我试图获取价值和属性的方式:

func getWarnings(root *xmlpath.Node, xpath xpath_OC) []Warning {
    warnings := []Warning{}
    v, _ := xmlpath.Compile(xpath.WarningsBase)
    WarningsBaseIter := v.Iter(root)
    for WarningsBaseIter.Next() {
        rawOffer := WarningsBaseIter.Node()
        warning := Warning{
            Value: GetString("", xpath.Warning, rawOffer),
            Attr:  GetString("", xpath.WarningAttr, rawOffer),
        }
        warnings = append(warnings, warning)
    }
    return warnings
}
func GetString(ExpressionPrefix string, XPathExpression string, Node *xmlpath.Node) string {
    Expr := []string{ExpressionPrefix, XPathExpression}
    pathString := strings.Join(Expr, "")
    if pathString != "BLANK" {
        Path, err := xmlpath.Compile(pathString)
        if err == nil {
            Value, _ := Path.String(Node)
            return Value
        }
    }
    return ""
}

我能够获得ShortText,但不能获得价值。我一直在检查错误,在终端上显示Path, err := xmlpath.Compile(pathString)的结果,显示的错误是compiling xml path "":0: empty path

任何解决方案?
感谢。

1 个答案:

答案 0 :(得分:0)

xmlquery包支持通过XPath表达式从XML中提取数据。

package main

import (
    "fmt"
    "strings"

    "github.com/antchfx/xmlquery"
)

func main() {
    xmlStr := `<?xml version="1.0"?><Warnings><Warning Type="309" ShortText="Unfulfilled Paid Service 1">Unable to book seat 1</Warning></Warnings>`
    doc, _ := xmlquery.Parse(strings.NewReader(xmlStr))
    nodes := xmlquery.Find(doc, "//Warning")
    for _, node := range nodes {
        fmt.Println(node.SelectAttr("ShortText"))
        fmt.Println(node.InnerText)
    }
}