2014-11-04 96 views
0

我使用PHP爲名稱空間URL創建了我們的客戶之一的XML響應。我期待輸出如下,將名稱空間添加到XML

<?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> 

但是,通過使用下面的代碼,

<?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: 演示是在這裏,http://codepad.org/11W9dLU9

這裏的問題是,第三個屬性是PHP函數setAttributeNS的強制屬性。所以,我得到的輸出,

<?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> 

所以,反正是有刪除ns3:schemaLocationns2:schemaLocation這與空值來嗎?我GOOGLE了很多,但無法找到任何有用的答案。

對此的任何想法都會很棒。請幫忙。

+0

可能重複,與「純DOM」?](http://stackoverflow.com/questions/26594261/how-to-set-namespace-xmlns-declaration-at-root-tag-with-pure-dom) – ThW 2014-11-04 12:05:00

+1

xmlns的命名空間: *屬性不是它的值:http://stackoverflow.com/a/26594433/2265374 – ThW 2014-11-04 12:06:53

回答

-1

你創建這個屬性:

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

刪除此行,他們將被刪除。

如果你想添加一些的xmlns沒有在代碼中使用,它是:

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

閱讀本評論:http://php.net/manual/pl/domdocument.createattributens.php#98210

在根標籤[如何設置命名空間(的xmlns)聲明的
+0

嗨,這是拋出一個錯誤。 http://codepad.org/z6mLH63c – Stranger 2014-11-04 10:50:16

+0

添加此行後:$ root = $ doc-> appendChild($ root);在你的代碼中 – Styx 2014-11-04 13:25:49

相關問題