(XML) appendChild adds tag prefix when importing node with xmlns attribute
I am trying to import XML from one document to another. This generally works fine, as demonstrated:
PHP Code:
<?php
header("Content-Type: application/xml");
$xml1 = "<beer><guiness>yum</guiness></beer>";
$xml2 = "<franziskaner><div>delicious</div></franziskaner>";
$doc1 = new DOMDocument();
$doc1->loadXML($xml1);
$doc2 = new DOMDocument();
$doc2->loadXML($xml2);
$doc1->documentElement->appendChild($doc1->importNode($doc2->documentElement,TRUE));
die($doc1->saveXML());
?>
The output is good:
Code:
<beer>
<guiness>yum</guiness>
<franziskaner>
<div>delicious</div>
</franziskaner>
</beer>
The problem begins when the imported XML has a node with an xmlns attribute:
PHP Code:
$xml2 = "<franziskaner><div xmlns=\"http://www.w3.org/1999/xhtml\">delicious</div></franziskaner>";
What happens to the output in this case, is all HTML nodes are then prefixed with "default":
Code:
<beer>
<guiness>yum</guiness>
<franziskaner xmlns:default="http://www.w3.org/1999/xhtml">
<default:div xmlns="http://www.w3.org/1999/xhtml">delicious</default:div>
</franziskaner>
</beer>
How can I import the XML "as is" without the "default" prefix?
Thanks
Aaron
I believe this is specific to PHP, as I tested the same code in C# with no issues.
Re: (XML) appendChild adds tag prefix when importing node with xmlns attribute
well, you're importing an XML namespace (xmlns attribute) but you're not naming your namespace. this is causing PHP to name it default. if you name it, everything works great (as far as I can tell):
PHP Code:
$xml2 = <<<XML
<franziskaner>
<div xmlns:mynamespace="http://www.w3.org/1999/xhtml">
delicious
</div>
</franziskaner>
XML;
you might also want to read more here.
and, for the record, I don't know if a namespace name is actually required or anything. but that makes your code work fine.
Re: (XML) appendChild adds tag prefix when importing node with xmlns attribute
It is perfectly fine to not name a namespace. This is called a default namespace and has the equivalent effect of giving that namespace to the element and all child elements. This can save prefixing lots of child elements.
It is documented in the same link you just provided
http://www.w3schools.com/XML/xml_namespaces.asp
I am having the same problem. Importing the nodes seems to create an unnecessary namespace called default. Tho the XML is actually logically the same, it looks messy with all those default prefixes everywhere. There must be a way of normalising out the default namespace and converting it back to using xmlns='xxx' format.
Thanks