将php脚本移植到golang时遇到问题。
golang中是否有类似于php的方法:
$processRefList = $faceContainer->getElementsByTagName('processRef');
有一个xml文件,其中包含大量名为processRef
的嵌套元素。
所以我需要收集所有这些元素而不处理嵌套结构树。
这是xml的一个示例部分:
<face>
<processes>
<process group="1" type="regular"/>
<process group="2" type="spotUV" state="off"/>
</processes>
<assets>...</assets>
<groups>
<group id="1">
<assetRefs>
<imageRef ref="1" x="0" y="0" id="8">
<processRefs>
<!-- This applies spotUV to this asset and removes the regular process. -->
<processRef ref="1" state="off"/>
<processRef ref="2" state="on"/>
</processRefs>
</imageRef>
<textRef ref="1" x="161" y="41" id="7"/>
<textRef ref="2" x="160" y="55" id="6">
<processRefs>
<!-- This applies spotUV to this asset and also leaves regular process applied. -->
<processRef ref="2" state="on"/>
</processRefs>
</textRef>
</assetRefs>
</group>
<group id="2">...</group>
</groups>
答案 0 :(得分:0)
我写了一个可以处理这个用例的包:
package main
import (
"github.com/89z/mech"
"os"
)
func main() {
f, err := os.Open("file.xml")
if err != nil {
panic(err)
}
defer f.Close()
doc, err := mech.Parse(f)
if err != nil {
panic(err)
}
ref := doc.ByTag("processRef")
for ref.Scan() {
state := ref.Attr("state")
println(state)
}
}
结果:
off
on
on
答案 1 :(得分:-1)
////store all xml data in var response
type XMLQuery struct {
Loc string `xml:",chardata"`
}
var l XMLQuery
decoder := xml.NewDecoder(strings.NewReader(string(response))) //store
all xml data in var response
for {
token, _ := decoder.Token()
if token == nil {
break
}
switch Element := token.(type) {
case xml.StartElement:
if Element.Name.Local == "processRef" {
fmt.Println("Element name is : ", Element.Name.Local)
err := decoder.DecodeElement(&l, &Element)
if err != nil {
fmt.Println(err)
}
attrVal :=l.Loc
fmt.Println("Title: ", attrVal)
}}}
答案 2 :(得分:-3)
试试这个
$extractvar = new DOMDocument();
$extractvar ->load("yourfile");
$itemextract= $extractvar ->getElementsByTagName("faceContainerRefs");
foreach( $itemextract as $value )
{
$var1= $value->getElementsByTagName("faceContainerRef ");
$var= $var1->item(0)->nodeValue;
}