dongpo2340 2019-03-19 17:37
浏览 5
已采纳

解组时是否可以合并没有专用根元素的XML子节点?

I have an XML structure to work with were a part looks like

   <Rights>
      <Name>NAS</Name>
      <Access>2</Access>
      <Name>App</Name>
      <Access>1</Access>
   </Rights>

This is (obviously) a list, and it is guaranteed that it contains of pairs Name, Access (and always in that particular order). My question: Can I use the encoding/xml package's Unmarshal function to unmarshal Name and Access in a single struct?

Consider the following example:

package main

import (
    "encoding/xml"
    "fmt"
)

var XML = []string{`
?xml version="1.0" encoding="UTF-8"?>
<SessionInfo>
   <SID>abc123</SID>
   <Rights>
      <Name>NAS</Name>
      <Access>2</Access>
      <Name>App</Name>
      <Access>1</Access>
   </Rights>
</SessionInfo>
`,`
<SessionInfo>
   <SID>def456</SID>
   <Rights />
</SessionInfo>
`}

type Right struct {
    Name string
    Access int
}

type SessionInfo struct {
    XMLName   xml.Name `xml:"SessionInfo"`
    SID       string
    Rights    []Right
}

func main() {
    for _,entry := range XML {
        info := SessionInfo{}
        if err := xml.Unmarshal([]byte(entry), &info); err != nil {
            fmt.Println("Marshal failed", err.Error())
            continue
        }
        fmt.Printf("%+v
", info)
    }
}

This doesn't work as expected:

// Only the first value is found
{SID:abc123 Rights:[{Name:App Access:1}]} 
// One (not existing) value was found and the struct's zero value was used
{SID:def456 Rights:[{Name: Access:0}]}

I could (and this works) define the properties independent of each other like

Names []string `xml:"Rights>Name"`
Accesses []int `xml:"Rights>Access"`

But I'd prefer the structure format of the first version without converting them manually.

Is there a way to get the expected result?

  • 写回答

1条回答 默认 最新

  • duanbimo7212 2019-03-27 14:09
    关注

    I'm using XPath library xmlquery not Go marshal/unmash method.

    package main
    
    import (
        "fmt"
        "strings"
    
        "github.com/antchfx/xmlquery"
    )
    
    func main() {
        s := `
    ?xml version="1.0" encoding="UTF-8"?>
    <SessionInfo>
       <SID>abc123</SID>
       <Rights>
          <Name>NAS</Name>
          <Access>2</Access>
          <Name>App</Name>
          <Access>1</Access>
       </Rights>
    </SessionInfo>
    `
        doc, err := xmlquery.Parse(strings.NewReader(s))
        if err != nil {
            panic(err)
        }
        for _, elem := range xmlquery.Find(doc, "//SessionInfo") {
            sid := xmlquery.FindOne(elem, "SID")
            fmt.Printf("sid: %s
    ", sid.InnerText())
            for _, name := range xmlquery.Find(elem, "Rights/Name") {
                fmt.Printf("name: %s
    ", name.InnerText())
            }
        }
    }
    
    

    output

    sid: abc123
    name: NAS
    name: App
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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