将xmlns:xsi属性名称空间添加到根元素时出错

时间:2012-02-15 06:29:28

标签: php dom xsd

我有一个名为sample.xml的xml

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

我正在尝试通过我的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";
}
?>

当我运行代码时出现以下错误

  

致命错误:带有消息'命名空间的未捕获异常'DOMException'   /var/www/xsd/test_sample.php:20中的错误'堆栈跟踪:#0   /var/www/xsd/test_sample.php(20):   DOMDocument-&gt; createAttributeNS('http://www.w3.o ...','xmlns:xsi')#1   {main}在第20行的/var/www/xsd/test_sample.php中抛出

如果我注释掉行$doc->createAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xmlns:xsi');,代码运行正常但是我无法验证xml,因为它显示sample.xml is invalid

有人可以帮我处理这段代码吗?

2 个答案:

答案 0 :(得分:2)

我要解决的第一件事就是在appendChild上使用document element。如果没有,则创建属性但不将其附加到树上。

要进行验证,请查看this link

答案 1 :(得分:1)

关于Searock在使用createAttribute时有必要使用appendChild而不是在使用createAttributeNS时不清楚的原因。

两个函数的内部功能设计不同,即使它们的名称相似:

createAttributeNS()会自动将NameSpace属性附加到文档中。

createAttribute()必须附加appendChild()。

相关问题