How to specify namespace and schema location in an XML?

My goal is to create an XML that is correctly referencing an XSD file describing the structure while both files use namespaces (the XML by setting the default namespace in the xmlns attribute).

I can specify xsi:noNamespaceSchemaLocation attribute in the XML and it works at least in some validators (like http://www.validome.org/xml/validate/). But when I try to add namespaces the validator returns errors (like: Can not find declaration of element 'note'.)

The final versions of the test files I prepared are attached below. I tested it with xmllint like:

xmllint example.xml --schema example.xsd

and it worked, but I specified the schema location in a parameter. My question is: is the XML file correctly referring the XSD and is it correctly using the namespace? Why the validator returns an error?

example.xml:

<?xml version="1.0" encoding="UTF-8"?>
<note
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="example.xsd"
        xmlns="http://example/note"
>
        <from>Jacek</from>
        <to>Agatka</to>
        <body>Kocham cię!</body>
</note>

example.xsd:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema
       xmlns:xsd="http://www.w3.org/2001/XMLSchema"
       xmlns="http://example/note"
       targetNamespace="http://example/note"
>
       <xsd:element name="note">
               <xsd:complexType>
                       <xsd:sequence>
                               <xsd:element ref="from"/>
                               <xsd:element ref="to"/>
                               <xsd:element ref="body"/>
                       </xsd:sequence>
               </xsd:complexType>
      </xsd:element>

      <xsd:element name="from" type="xsd:string"/>

      <xsd:element name="to" type="xsd:string"/>

      <xsd:element name="body" type="xsd:string"/>

</xsd:schema>

The schemaLocation attribute should specify also the namespace:

<?xml version="1.0" encoding="utf-8"?>
<note
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://example/note example.xsd"
  xmlns="http://example/note">
  <from>Jacek</from>
  <to>Agatka</to>
  <body>Kocham cię!</body>
</note>

See documentation here.

链接地址: http://www.djcxy.com/p/58796.html

上一篇: 以编程方式清除/忽略XML中的名称空间

下一篇: 如何在XML中指定名称空间和模式位置?