...">

Scala XML \\ copies the xmlns. Why and how can I stop it?

In the Scala REPL:

val input = <outerTag xmlns="http://xyz"> <innerTag> </innerTag> </outerTag>

input\\@"innerTag"

      

=>

<innerTag xmlns="http://xyz"> </innerTag>

      

How do I stop Scala from doing this? Why can't he give it to me <innerTag> </innerTag>

? How can I stop this event (or just remove the attributes xmlns

)?

Thank!

Joe

Clarification: My common goal is to strip the XML file and recombine it. So this node will be taken from under the root node (which has the xmlns attribute) and then integrated back into the document under the root, which has xmlns again.

+2


source to share


4 answers


Your original document <innerTag>

has a logical namespace "http://xyz"

since its parent <outerTag>

had that namespace. How XML namespaces work.

When you request an element <innerTag>

yourself, Scala copies the namespace declaration from the parent <outerTag>

, because the namespace is a logical part <innerTag>

, even if it wasn't explicitly stated in the original document.



If you want to remove the namespace, you need to do some additional processing.

+3


source


Use named parameter and Elem.copy () in Scala 2.8.0:



scala> import scala.xml._
import scala.xml._

scala> val outer = <outerTag xmlns="http://xyz"><innerTag></innerTag></outerTag>
outer: scala.xml.Elem = <outerTag xmlns="http://xyz"><innerTag></innerTag></outerTag>

scala> outer \\ "innerTag" map { case e: Elem => e.copy(scope = TopScope) }
res0: scala.xml.NodeSeq = <innerTag></innerTag>

      

+3


source


God, I hope I missed something. It can't be awkward!
import scala.xml._
import scala.xml.tranform._

val rw = new RewriteRule { 
  override def transform(n: Node) = n match {
    case Elem(p, l, a, s, children@ _*) => Elem(p, l, a, TopScope, children: _*)
    case x => x
  }
  override def transform(ns: Seq[Node]): Seq[Node] = ns flatMap transform
}
val rt = new RuleTransformer(rw)

val input = <outerTag xmlns="http://xyz"> <innerTag> </innerTag> </outerTag>

val result = input \\ "innerTag" map rt

      

Or am I too flawed with Scala to think it's too complicated?

+1


source


I ran into a similar problem when applying transformations to document sub-nodes. As a result, all nodes had xmlns on nodes.

After completing the conversion, I used the following function to "clean up" the document for printing. In the meantime, there is no need to know about it. ”

def transformForPrinting(doc : Elem) : Elem = { 
 def stripNamespaces(node : Node) : Node = {
     node match {
         case e : Elem => 
             e.copy(scope = TopScope, child = e.child map (stripNamespaces))
         case _ => node;
     }
 }
 doc.copy( child = doc.child map (stripNamespaces) )}

      

+1


source







All Articles