2012-06-01 33 views
2

我想動態創建xml架構與PHP,但我遇到名稱空間的問題。我想要做的是有一個函數返回xsd:元素並將它們添加到xsd:sequence節點。將節點導入DOMDocument現有命名空間

我創建的xsd:在該函數中的臨時DOM文檔元素節點,我需要指定XSD命名空間「的xmlns:XSD =」 http://www.w3.org/2001/XMLSchema」否則「XSD :'bit is removed。然後我從節點文件中提取所需的節點並使用importNode()複製到存在的DOMDocument。問題是完整的xmlns字符串被附加到從創建元素。

初始DOM文檔

<?xml version="1.0" encoding="UTF-8"?> 
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <xsd:complexType name="UserType"> 
    <xsd:sequence> 
    // add elements here 
    </xsd:sequence> 
</xsd:complexType> 
</xsd:schema> 

溫度的DOMDocument我用它來收集領域

<?xml version="1.0" encoding="UTF-8"?> 
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <xsd:element type="xsd:string" name="Field1"/> 
    <xsd:element type="xsd:string" name="Field2"/> 
    <xsd:element type="xsd:string" name="Field3"/> 
</xsd:schema> 

我得到

<?xml version="1.0" encoding="UTF-8"?> 
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"/> 
    <xsd:complexType name="UserType"/> 
    <xsd:sequence/> 
     <xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" type="xsd:string" name="Field1"/> 
     <xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" type="xsd:string" name="Field2"/> 
     <xsd:element xmlns:xsd="http://www.w3.org/2001/XMLSchema" type="xsd:string" name="Field3"/> 
    </xsd:sequence/> 
    </xsd:complexType/> 
</xsd:schema/> 

什麼如何導入到現有的命名空間?

+0

*所有*您的xml聲明在最後都有一個'?/>'......這是一個錯字嗎? –

+0

是的,這是一個錯字。因爲我無法讓複製/粘貼代碼正確顯示,所以我正在調整格式,然後我發現你需要一個空行代碼塊。 – RoboDave

回答

2

我需要什麼做的就是確保我創建_ ALL _使用第一DOM文檔中的元素:

createElementNS('http://www.w3.org/2001/XMLSchema','xsd:sequence') 

而不是:

createElement('xsd:sequence') 

我只是在需要xmln的第一個元素上使用createElementNS的聲明。

1

似乎工作? http://codepad.viper-7.com/SueilL

<?php header('content-type: text/plain;charset=utf-8'); 



$s1 = '<?xml version="1.0" encoding="UTF-8"?> 
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <xsd:complexType name="UserType"> 
    <xsd:sequence> 
    </xsd:sequence> 
</xsd:complexType> 
</xsd:schema> 

'; 
$s2 = '<?xml version="1.0" encoding="UTF-8"?> 
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <xsd:element type="xsd:string" name="Field1"/> 
    <xsd:element type="xsd:string" name="Field2"/> 
    <xsd:element type="xsd:string" name="Field3"/> 
</xsd:schema> 
'; 


$ns = 'http://www.w3.org/2001/XMLSchema'; 

$doc = new DOMDocument(); 
$doc->loadXML($s1); 
$seqElem = $doc->getElementsByTagNameNS($ns, "sequence")->item(0); 

$d = new DOMDocument(); 
$d->loadXML($s2); 
foreach ($d->getElementsByTagNameNS($ns, "*") as $e) { 
    $seqElem->appendChild($doc->importNode($e)); 
} 


echo $doc->saveXML(); 
+0

感謝您使用NS功能的反饋,將我指向正確的方向。 – RoboDave

+0

今天救了我的屁股。謝謝。 –