Scala - Completely remove namespace from xml

I have 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 completely remove all namespaces, no matter where they are. How do I do this with Scala?

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

I searched for RuleTransform and copied attributes, etc., but I can either remove the namespaces or delete the attributes, but not delete the namespace and save the attributes.

+4
source share
2 answers

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

 xmlElem.copy(scope = TopScope) 

However, this is a constant recursive structure, so you need to do it in a recursive way:

 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, deleting the region on all nodes. You may need to remove the region from the attributes.

+6
source

Next, you must recursively remove namespaces from both elements and attributes.

 def removeNamespaces(node: Node): Node = { node match { case elem: Elem => { elem.copy( scope = TopScope, prefix = null, attributes = removeNamespacesFromAttributes(elem.attributes), child = elem.child.map(removeNamespaces) ) } case other => other } } def removeNamespacesFromAttributes(metadata: MetaData): MetaData = { metadata match { case UnprefixedAttribute(k, v, n) => new UnprefixedAttribute(k, v, removeNamespacesFromAttributes(n)) case PrefixedAttribute(pre, k, v, n) => new UnprefixedAttribute(k, v, removeNamespacesFromAttributes(n)) case Null => Null } } 

It worked, at least in the following test case:

 <foo xmlns:xoox="http://example.com/xoox"> <baz xoox:asd="first">123</baz> <xoox:baz xoox:asd="second">456</xoox:baz> </foo> 
+1
source

Source: https://habr.com/ru/post/1435546/


All Articles