dt2002 2015-06-08 08:26
浏览 142
已采纳

如何使用Go获取XML元素的所有属性?

I am trying to parse xml content along with all the attributes of an XML element like this

type Node struct {
  XMLName xml.Name
  Attributes []xml.Attr `xml:",attr"`
  BodyElements string `xml:",innerxml"`
  Nodes   []Node `xml:",any"`
}

var xmldata = []byte("<div><div data-id=\"images/6C7161080\" data-imagesize=\"medium\" data-alignment=\"none\"></div></div>")

func walk(nodes []Node, f func(Node) bool) {
  for _, n := range nodes {
    if f(n) {
        walk(n.Nodes, f)
    }
  }
}


func main() {

  buf := bytes.NewBuffer(xmldata)
  dec := xml.NewDecoder(buf)

  var n Node
  err := dec.Decode(&n)
  if err != nil {
    panic(err)
  }

  walk([]Node{n}, func(n Node) bool {
    if n.XMLName.Local == "p" {
        fmt.Println(string(n.BodyElements))
    } else if n.XMLName.Local == "div"{
        fmt.Println(string(n.BodyElements))
        fmt.Println(len(n.Attributes))
    }
    return true
  })
}

But the value of len(n.Attributes) is always 0. What can I do to get all the attributes in the given element. NOTE: The attribute names are not constant as sometime the element can be a "div" tag or "img" tag or something else. So I can't use the attribute name as

DataId string `xml:"data-id,attr"`
  • 写回答

1条回答 默认 最新

  • duandi8852752 2015-06-08 10:25
    关注

    The fundamental problem is that unmarshalling XML to your struct Node doesn't work. Your BodyElements captures the whole content of your root node and nothing is unmarshaled to your Nodes. (Btw: Adding a simple fmt.Printf would have revealed this.)

    Why do you try to write your own XML unmarshalling/parsing code? You will fail. Just use the Decoder and the Token method to parse your XML by hand, one token after each other, populating your tree manually. And: If your XML actually is HTML you might want to parse it with package html.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?