php - How to completely remove a namespace using DOMDocument -


given xml following, how can remove particular namespace, including declaration, each element?

<?xml version="1.0" encoding="utf-8"?> <document xmlns:my-co="http://www.example.com/2015/co">   <my-namespace:first xmlns:my-namespace="http://www.example.com/2015/ns">     <element my-namespace:id="1">     </element>   </my-namespace:first>   <second>     <my-namespace:element xmlns:my-namespace="http://www.example.com/2015/ns" my-co:id="2">     </my-namespace:element>   </second> </document> 

notice there no xmlns:my-namespace declaration @ root level , 2 declarations in different parts , levels of xml structure.

how can efficiently remove namespace my-namespace without having check each node in code?

this xml should afterwards:

<?xml version="1.0" encoding="utf-8"?> <document xmlns:my-co="http://www.example.com/2015/co">   <first>     <element id="1">     </element>   </first>   <second>     <element my-co:id="2">     </element>   </second> </document> 

the following code trick:

// removes namespace $ns elements in domdocument $doc function remove_dom_namespace($doc, $ns) {   $finder = new domxpath($doc);   $nodes = $finder->query("//*[namespace::{$ns} , not(../namespace::{$ns})]");   foreach ($nodes $n) {     $ns_uri = $n->lookupnamespaceuri($ns);     $n->removeattributens($ns_uri, $ns);   } }  // usage: $mydoc = new domdocument(); $mydoc->load('test.xml'); // load "before" xml remove_dom_namespace($mydoc, 'my-namespace');  // prints above "after" xml echo $mydoc->savexml(null, libxml_noemptytag); 

the xpath query finds nodes have namespace node called $ns parent node doesn't have same namespace. find /document/my-namespace:first , /document/second/my-namespace:element not /document/my-namespace:first/element because parent has namespace my-namespace. code removes specified namespace each element found. removing namespace element automatically removes of children too.

a lot of real world xml documents have xmlns declarations on root element code handles them anywhere.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -