Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - Completely remove namespace from xml

Tags:

xml

scala

I have some xml:

<item name="ed" test="true"
  xmlns="http://www.somenamespace.com"
  xmlns:xsi="http://www.somenamespace.com/XMLSchema-instance">
  <blah>
     <node>value</node>
  </blah>
</item>

I want to go through this xml and remove all namespaces completely, no matter where they are. How would I do this with Scala?

 <item name="ed" test="true">
  <blah>
     <node>value</node>
  </blah>
</item>

I've been looking at RuleTransform and copying over attributes etc, but I can either remove the namespaces or remove the attributes but not remove the namespace and keep the attributes.

like image 836
ed. Avatar asked Sep 21 '12 17:09

ed.


People also ask

How remove all namespaces from XML in XSLT?

Example XSLT stylesheet that removes all namespaces insert into XMLTRANS (XSLID, XSLT) values ( 1, ' <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <!

How do I remove namespace prefix?

Once a namespace prefix is created, it cannot be changed or deleted. The workaround is to move all your code to a new Developer Organization, where you can setup the desired Namespace Prefix.

How to remove namespace from xml in oracle?

You can use XMLTRANSFORM to apply an XSLT (Transformer) to remove the namespaces.


1 Answers

The tags are Elem objects and the namespace is controlled by the scope value. So to get rid of it you could use:

xmlElem.copy(scope = TopScope)

However this is an immutable recursive structure so you need to do this in a recursive manner:

import scala.xml._

def clearScope(x: Node):Node = x match {
  case e:Elem => e.copy(scope=TopScope, child = e.child.map(clearScope))
  case o => o
}

This function will copy the XML tree removing the scope on all the nodes. You may have to remove the scope from the attributes too.

like image 198
Thomas Avatar answered Oct 27 '22 17:10

Thomas