简体   繁体   中英

Following a schema without specifying it in the xml

If I have a file like this (note that it does not point to a schema): data.xml

<?xml version="1.0"?>
<data>
    <item>
        <note>2008</note>
        <title>1</title>
    </item>
</data>

and a schema like this:

myschema.xsd

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="data">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="item" maxOccurs="unbounded">
        <xs:complexType>
          <xs:all>
            <xs:element name="title" type="xs:string"/>
            <xs:element name="note" type="xs:string"/>
          </xs:all>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>

</xs:schema>

I can specify the schema to a validator:

$ xmllint --schema myschema.xsd data.xml
<?xml version="1.0"?>
<data>
    <item>
        <note>2008</note>
        <title>1</title>
    </item>
</data>
data.xml validates

and it works correctly. However, in most examples I read online, the schema is specified in the xml file directly, with things like:

<hockeyTeam xmlns="http://www.nhl.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

What is the advantage of specifying the schema for a particular element like that? Is the schema used at any point other than validation?

What you've shown is not an example of specifying the schema for a particular element , at least not the way most people would relate to this statement - I'm saying it since you're not showing any XSI attributes that deal with schema location.

Have a look at noNamespaceSchemaLocation and schemaLocation attributes. These two would do that for schemas without, and with, a namespace, respectively.

The advantage you may get depends on the context. In secure production environments, no one cares about these attributes; ie they would not be "followed". Editors might be happy to use them, considering them as a way to apply schema when other mechanism don't exist, such as explicit schema assignment, schema catalogs, etc. Some XML processors, XSD-aware, might have options you can turn on and off, to handle these attributes. Other processors, don't.

In general, I don't really see using this as an "advantage", due to the more problems it creates rather than solves. One is where people exchange XMLs (as part of a documentation package), but then the location of the XSDs in the above mentioned attributes is not the same on the different machines where people are looking at them, or due to the use of different XML processors.

I would recommend to maybe use them if they work for you, but avoid generating/releasing XML to others with these attributes in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM