Parsing partial data
nizarayari opened this issue · 2 comments
nizarayari commented
Hi there,
I would like to know if there is way to parse partial data located in different places in the xml doc. For example, I want to got from
`<a>
<b>
<c>c</c>
<d>d</d>
</b>
<e>
<x>x</x>
<y>y</y>
<z>z</z>
</e>
<f>f</f>
<g>g</g>
</a>`
to
`<a>
<b>
<c>c</c>
</b>
<e>
<x>x</x>
</e>
</a>`
Is there any easy way to do that plz?
Thanks in advance!
clbanning commented
You can use mv.NewMap("a.b.c", "a.e.x"). Or spec a bunch of XML docs, and do something like:
package main
import (
"fmt"
"github.com/clbanning/mxj"
)
var source = []byte(`<a>
<b>
<c>c</c>
<d>d</d>
</b>
<e>
<x>x</x>
<y>y</y>
<z>z</z>
</e>
<f>f</f>
<g>g</g>
</a>`)
var wants = map[string][]string{
"one": {
"a.b.c",
"a.e.x",
},
"two": {
"a.b.d",
"a.e.y",
"a.e.z",
},
"three": {
"a.f",
"a.g",
},
}
func main() {
m, err := mxj.NewMapXml(source)
if err != nil {
fmt.Println("err:", err)
return
}
n, err := m.NewMap(wants["one"]...)
if err != nil {
fmt.Println("err:", err)
return
}
target, err := n.XmlIndent("", " ")
if err != nil {
fmt.Println("err:", err)
return
}
fmt.Println(string(target))
// the rest of the wants
n, _ = m.NewMap(wants["two"]...)
target, _ = n.XmlIndent("", " ")
fmt.Println(string(target))
n, _ = m.NewMap(wants["three"]...)
target, _ = n.XmlIndent("", " ")
fmt.Println(string(target))
}
Prints:
<a>
<b>
<c>c</c>
</b>
<e>
<x>x</x>
</e>
</a>
<a>
<b>
<d>d</d>
</b>
<e>
<y>y</y>
<z>z</z>
</e>
</a>
<a>
<f>f</f>
<g>g</g>
</a>
nizarayari commented
Thanks a lot @clbanning