猿问

Golang - 如何将 XML 文件的一部分提取为字符串?

我的 XML 看起来像这样:


<a>

  <b>

    <c>

      <d>TEXT</d>

   </c>

  </b>

</a>

我知道如何通过 xml.Unmarshal 函数分离这段代码,但是有没有办法只在一定深度内执行 Unmarshal 操作?例如,如果我想获取一个显示“TEXT”的字符串并将其传递给另一个函数?我尝试给一个子字符集对象,但它仍然尝试解析 XML 的其余部分......


拉丁的传说
浏览 150回答 2
2回答

白衣染霜花

我认为这就是您要问的(也请考虑您的评论)。package mainimport (&nbsp; &nbsp; "encoding/xml"&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; type Result struct {&nbsp; &nbsp; &nbsp; &nbsp; Value&nbsp; string `xml:"b>c>d"`&nbsp; &nbsp; }&nbsp; &nbsp; v := Result{"none"}&nbsp; &nbsp; data := `&nbsp; &nbsp; &nbsp; &nbsp; <a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <b>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <c>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <d>TEXT</d>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </c>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </b>&nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; `&nbsp; &nbsp; err := xml.Unmarshal([]byte(data), &v)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("error: %v", err)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("Value: %v\n", v.Value)}输出:Value: TEXT更新:在 lanZG 的评论之后func main() {&nbsp; &nbsp; type InnerResult struct {&nbsp; &nbsp; &nbsp; &nbsp; Value string `xml:",innerxml"`&nbsp; &nbsp; }&nbsp; &nbsp; type Result struct {&nbsp; &nbsp; &nbsp; &nbsp; B InnerResult `xml:"b"`&nbsp; &nbsp; }&nbsp; &nbsp; v := Result{InnerResult{"none"}}&nbsp; &nbsp; data := `&nbsp; &nbsp; &nbsp; &nbsp; <a>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <b>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <c>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <d>TEXT</d>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </c>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </b>&nbsp; &nbsp; &nbsp; &nbsp; </a>&nbsp; &nbsp; `&nbsp; &nbsp; err := xml.Unmarshal([]byte(data), &v)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("error: %v", err)&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Printf("Value: %v\n", v.B.Value)}输出:Value:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <c>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <d>TEXT</d>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </c>
随时随地看视频慕课网APP

相关分类

Go
我要回答