简体   繁体   中英

Adding namespace to XML

I'm creating XML response for the one of our clients with the namespace URLs in that using PHP. I'm expecting the output as follows,

<?xml version="1.0" encoding="UTF-8"?>
<ns3:userResponse xmlns:ns3="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://www.w3.org/2001/XMLSchema">
   <Content>
      <field1>fieldvalue1</field1>
   </Content>
</ns3:userResponse>

But by using the following code,

<?php
// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');

// create root node
$root = $doc->createElementNS('http://www.w3.org/2001/XMLSchema-instance', 'ns3:userResponse');
$root = $doc->appendChild($root);

$root->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'ns1:schemaLocation','');
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema', 'ns2:schemaLocation','');

// add node for each row
$occ = $doc->createElement('Content');
$occ = $root->appendChild($occ);


$child = $doc->createElement("field1");
$child = $occ->appendChild($child);

$value = $doc->createTextNode('fieldvalue1');
$value = $child->appendChild($value);


// get completed xml document
$xml_string = $doc->saveXML();

echo $xml_string;

DEMO: The demo is here, http://codepad.org/11W9dLU9

Here the problem is, the third attribute is mandatory attribute for the setAttributeNS PHP function. So, i'm getting the output as,

<?xml version="1.0" encoding="UTF-8"?>
<ns3:userResponse xmlns:ns3="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://www.w3.org/2001/XMLSchema" ns3:schemaLocation="" ns2:schemaLocation="">
   <Content>
      <field1>fieldvalue1</field1>
   </Content>
</ns3:userResponse>

So, is there anyway to remove that ns3:schemaLocation and ns2:schemaLocation which is coming with empty value? I googled a lot but couldn't able to find any useful answers.

Any idea on this would be so great. Please help.

You create this attributes:

$root->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'ns1:schemaLocation','');
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema', 'ns2:schemaLocation','');

remove this lines and they will be removed.

If you want to add some xmlns without using it in code is:

$attr_ns = $doc->createAttributeNS( 'http://www.w3.org/2001/XMLSchema', 'ns2:attr' );

Read this comment: http://php.net/manual/pl/domdocument.createattributens.php#98210

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM