2012-02-15 55 views
2

我有一個名爲sample.xml中錯誤:XSI屬性命名空間根元素

<?xml version="1.0"?> 
<note> 
     <to>Tove</to> 
      <from>Jani</from> 
      <heading>Reminder</heading> 
      <body>Don't forget me this weekend!</body> 
</note> 

和sample.xsd驗證sample.xml中

<?xml version="1.0"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
targetNamespace="http://www.w3schools.com" 
xmlns="http://www.w3schools.com" 
elementFormDefault="qualified"> 

     <xs:element name="note"> 
        <xs:complexType> 
          <xs:sequence> 
            <xs:element name="to" type="xs:string"/> 
            <xs:element name="from" type="xs:string"/> 
            <xs:element name="heading" type="xs:string"/> 
            <xs:element name="body" type="xs:string"/> 
          </xs:sequence> 
        </xs:complexType> 
     </xs:element> 

</xs:schema> 

我試圖XML通過我的php代碼驗證sample.xml,並且因爲sample.xml中沒有名稱空間,所以我從php代碼中添加了命名空間。

<?php 

error_reporting(E_ALL); 
ini_set('display_errors', 'On'); 

$file = 'sample.xml'; 
$schema = 'sample.xsd'; 
$doc = new DOMDocument(); 
$doc->load($file); 

$doc->createAttributeNS('http://www.w3schools.com', 'xmlns'); 
$doc->createAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xmlns:xsi'); 
$doc->createAttributeNS('http://www.w3schools.com sample.xsd', 'xsi:schemaLocation'); 

print $doc->saveXML(); 


if ($doc->schemaValidate($schema)) { 
     print "$file is valid.\n"; 
} else { 
     print "$file is invalid.\n"; 
} 
?> 

,當我運行代碼,我得到以下錯誤

Fatal error: Uncaught exception 'DOMException' with message 'Namespace Error' in /var/www/xsd/test_sample.php:20 Stack trace: #0 /var/www/xsd/test_sample.php(20): DOMDocument->createAttributeNS('http://www.w3.o...', 'xmlns:xsi') #1 {main} thrown in /var/www/xsd/test_sample.php on line 20

如果我註釋掉$doc->createAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xmlns:xsi');的代碼運行正常,但隨後我不能,因爲它說驗證XML sample.xml is invalid

有人能幫我解決這個問題嗎?

回答

2

我會修復的第一件事情就是在document element上也使用appendChild。沒有這一點,該屬性被創建,但不會附加到您的樹上。請致電this link

+0

你確定我不得不使用appendChild,因爲我試着評論'$ doc-> createAttributeNS('http://www.w3.org/2001/XMLSchema-instance','xmlns:xsi') ;'在我的代碼中,然後檢查xml,它仍然包含其餘的兩個命名空間。我會看看你提供的鏈接:) – Searock 2012-02-16 04:58:10

+0

是的,我確定;創建一個節點並不會將它附加到樹上 - 所有的DOM API都是這樣的:)... – 2012-02-16 12:09:54

+1

Wierd案例與我:)我不知道爲什麼,但'createAttributeNS'添加namesapce而不調用appendChild'。任何方式您的鏈接幫助了我很多。謝謝 – Searock 2012-02-17 05:29:04

1

Searock對澄清爲什麼需要在使用createAttribute時使用appendChild而不是在使用createAttributeNS時混淆的一點。

的兩個函數的內部功能設計不同,即使它們的名稱相似:

createAttributeNS()自動將命名空間屬性的文件。

createAttribute()必須附加appendChild()。