英文:
How to handle nested XML tags in Go?
问题
我正在尝试从蛋白质数据库(pdb)中解析查询响应。我一直在阅读Go语言的XML编码包,并了解如何处理标签,但我不知道如何处理嵌套标签。我从下面的代码中得到的输出如下:
<PDBdescription>
<PDB structureId="4HHB"....
</PDBdescription>
我该如何获取structureId的信息?因为它似乎与PDB标签相关联,而PDB标签位于PDBdescription标签内部。
// pdbRequest
package main
import (
"fmt"
"net"
"encoding/xml"
//"strings"
)
type PDB struct {
id string `xml:"PDBdescription>PDB structureId"`
XMLName xml.Name
}
func main() {
conn, err := net.Dial("tcp", "www.rcsb.org:http")
p := PDB{id:"NONE"}
if err != nil {
return
}
fmt.Fprintf(conn, "GET /pdb/rest/describePDB?structureId=4hhb HTTP/1.0\r\n\r\n")
status := make([]byte, 10000)
conn.Read(status)
xml.Unmarshal([]byte(status), &p)
fmt.Println(string(status))
fmt.Println(p.id)
}
我看到我的问题与这里的其他问题非常相似(很快会放入链接参考),但那里给出的答案似乎不是我的解决方案,因为我的标签有点不同。
英文:
I am trying to unmarshal a query response from the protein database (pdb). I have been reading on the XML encoding package of Go, and understand how to handle tags, but I do not know how to handle nested tags. I get as output from code below (cutout);
<PDBdescription>
<PDB structureId="4HHB"....
</PDBdescription>
How can I get the info on the structureId? for it seems that it is connected to PDB-tag, which is within the PDBdescription-tag?
// pdbRequest
package main
import (
"fmt"
"net"
"encoding/xml"
//"strings"
)
type PDB struct {
id string `xml:"PDBdescription">"PDB structureId"`
XMLName xml.Name
}
func main() {
conn, err := net.Dial("tcp", "www.rcsb.org:http")
p := PDB{id:"NONE"}
if err != nil {
return
}
fmt.Fprintf(conn, "GET /pdb/rest/describePDB?structureId=4hhb HTTP/1.0\r\n\r\n")
status := make([]byte, 10000)
conn.Read(status)
xml.Unmarshal([]byte(status), &p)
fmt.Println(string(status))
fmt.Println(p.id)
}
I see that my question is very similar to other questions here (putting in link references soon), but the answers given there seems not to be my solution because my tag is a bit different.
答案1
得分: 4
你可以在标记结构字段时使用,attr
修饰符。例如:
type PDB struct {
StructureId string `xml:"structureId,attr"`
}
type root struct {
Pdb PDB `xml:"PDBdescription>PDB"`
}
如果你解码到一个root
实例中,structureId
属性将被解码到嵌套的Pdb.StructureId
字段中。
不幸的是,目前无法将链式语法与,attr
修饰符结合使用,所以你需要使用嵌套结构。
这里有一个可工作的示例:http://play.golang.org/p/VhUBKKLfk4
英文:
You need can use the ,attr
modifier when tagging your struct field. For example:
type PDB struct {
StructureId string `xml:"structureId,attr"`
}
type root struct {
Pdb PDB `xml:"PDBdescription>PDB"`
}
If you decode into a root
instance, the structureId
attribute will be decoded into the nested Pdb.StructureId
field.
Unfortunately you can't combine the chaining syntax with the ,attr
modifier at this point, so you will need a nested struct.
Here is a working example: http://play.golang.org/p/VhUBKKLfk4
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论