antchfx / xmlquery

xmlquery is Golang XPath package for XML query.
https://github.com/antchfx/xpath
MIT License
444 stars 89 forks source link

xmlquery.FindOne for attributes is giving a new node without reference to parent #21

Closed vinaykumarponna closed 4 years ago

vinaykumarponna commented 4 years ago

xmlquery.FindOne is providing a new node. But, we cannot change the value of attribute and generate updated XML. So, if you can provide the Parent reference within attribute node, then we can iterate through attributes of Parent reference node and change the value of attribute.

zhengchun commented 4 years ago

@vinaykumarponna

[]Attr property of Node is a value type, if you want to update parent value,you should use for..loop.

doc, _ := xmlquery.Parse(strings.NewReader(`<html><a id="1" href="/">go</a></html>`))

n := xmlquery.FindOne(doc, "//a/@id")
p := n.Parent
for i := 0; i < len(p.Attr); i++ {
    if p.Attr[i].Name.Local == "href" {
        p.Attr[i].Value = "/go"
    }
}
    n = xmlquery.FindOne(doc, "//a")
    fmt.Println(n.OutputXML(true))