如何访问 Scala XML 中的父元素 [英] How to access parent element in Scala XML

查看:52
本文介绍了如何访问 Scala XML 中的父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scala.xml 包代表带有标签树节点的 XML.但是这棵树在 Scala 2.7 中是否是单向的,因为似乎无法访问给定 ElemElem 父级?这似乎同样适用于父 Document.例如,在 XOM 中,您有 getParentgetDocument 访问器来导航到树的根部.这可以用 Scala 的 XML API 来完成吗?

The scala.xml package represents XML with nodes of a labelled tree. But is this tree unidirectional in Scala 2.7, as there seems to be no way to access the Elem parent of a given Elem? The same seems to apply for parent Document. For example, in XOM you have getParent and getDocument accessors to navigate towards the root of the tree. Can this be done with Scala's XML API?

推荐答案

正如其他人所提到的,没有父链接可以使它们成为高效的不可变结构.例如:

As mentioned by others, there are no parent links to make them efficient immutable structures. For example:

scala> val a = <parent><children>me</children></parent>
a: scala.xml.Elem = <parent><children>me</children></parent>

scala> val b = a.child(0)
b: scala.xml.Node = <children>me</children>

scala> val c = <newparent>{b}</newparent>
c: scala.xml.Elem = <newparent><children>me</children></newparent>

scala> a
res0: scala.xml.Elem = <parent><children>me</children></parent>

scala> b
res1: scala.xml.Node = <children>me</children>

scala> c
res3: scala.xml.Elem = <newparent><children>me</children></newparent>

没有复制数据结构.b 指向的节点与 ac 指向的节点完全相同.如果它必须指向父级,那么当你在 c 中使用它时,你必须制作它的副本.

No data structure was copied. The node pointed to by b is the very same node pointed to by both a and c. If it had to point to a parent, then you'd have to make a copy of it when you used it in c.

要以您想要的方式在该数据结构中导航,您需要一个称为 Purely Applicative XML Cursor 的东西.

To navigate in that data structure the way you want, you need what is called a Purely Applicative XML Cursor.

这篇关于如何访问 Scala XML 中的父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆