Expanding on a question I asked earlier about how to iterate over a collection of nodes in scala.xml.Node found here
I wanted to take this 1 step further and ask how I could look up to a previous child inside a recursive function to get a value once I hit a specific situation
For example (the markup is here)
<html>
<head class="foo">
<title>Welcome</title>
</head>
<body>
<div>
<p>Foo</p>
</div>
</body>
</html>
With my current implementation (thanks to @knut-arne-vedaa)
def processNode(node: Node) {
if (node.isInstanceOf[Text]) {
if (node.text.contains("Welcome"))
{
//then inside here I want to go up to the prev element (head) and pull the class
}
}
node.child foreach processNode
}
I want to add another conditional to get the text “foo” from inside the class section
Any idea what I could add inside this if statement to pull this value directly? Also how can I return the String value from this fx? a break w/ a simple return line or ?
Note that the parent of the Text node in your example is actually the <title> node.
Since Nodes don’t have references to their parents, one way to access them is just to pass them with you when walking down the tree, like this:
Of course, this becomes unwieldy when you want to climb back up the tree to an arbitrary level. One approach to this is to wrap your nodes in a
SuperNodethat has an optional parent reference.For convenience, make an implicit function to convert nodes to SuperNodes in the default case of no parent.
Now you can navigate up the tree an arbitrary number of times, like this: