1

I got an xml document that I want to update and I'm looping through the nodes using a recursive function. However I'm having an issue with updating node attributes. I want to hide all the paths from the user and replacing them with a key. This is what I've got so far

XML document example:

<html>
    <head>
      <title>my document</title>
      <link rel="stylesheet" href="/styles/style.css"/>
    </head>
    <body>
      <a href="link1"></a>
      <img src="link2"/>
      <img src="link3"/>
      <img src="link1"/>
      <a href="link5"></a>
    </body>
  </html>

Which is passed through my recursive function which then calls updateNode function to update it

def processNode(n: Node){
    if(n.label == "a") {
          updateNode(n, "href")
      }
    }
    n.child foreach processNode
  }

def updateNode(n: Node, att: String) {
val k: Int = getKey(n.attribute(att).get.toString)   
if (k == c){ // if k == c then key does not exists
  list += (c -> n.attribute(att).get.toString())
  // update node
  c = c + 1
} else {
  // update node
}}

I've tested .attributes.remove and .attributes.append but they don't seem to be working. I'm assuming that I might need to use .copy but node data type doesn't have .copy.. Elem does

Joseph118
  • 505
  • 6
  • 21

1 Answers1

0

As I recognise you are using a SAX parser for parsing your XML document into memory! That is a parser / reader. In case you want to modify your loaded XML tree object graph ( i.e. in a more sophisticated way stepping from node to node adding attributes) on your heap so that you want to write it back to disk or send it through the wire after modifying, extending the tree structure then you can use JAXB libraries.

If you do not want to spend the time and you just need to change one single attribute to fix your tree then you can stay with the SAX parser but then you need to temp save and write the file (DataStream) back as string / text from a string buffer.

Gabor Jakab
  • 236
  • 2
  • 6
  • that was the plan stepping from node to node, I already have a recursive function for that and the att parameter for this functions accepts either src or href depends on the element. what i can't figure out is how to update the node. I've recently started using scala so i'm still in learning phase. I will take a look at JAXB libraries however – Joseph118 Sep 12 '15 at 08:34