Is it possible to use XML Schemas internally, just like DTDs?

早过忘川 提交于 2019-11-30 09:52:41

问题


I have the following XML file which includes internal DTD validation:

<?xml version="1.0"?>
<!DOCTYPE animals [
    <!ELEMENT animals (animal)*>
    <!ELEMENT animal (skin, noise, eyes, diet, class, weight, special_skill)>
    <!ELEMENT skin (#PCDATA)>
    <!ELEMENT noise (#PCDATA)>
    <!ELEMENT eyes (#PCDATA)>
    <!ELEMENT diet (#PCDATA)>
    <!ELEMENT class (#PCDATA)>
    <!ELEMENT weight (#PCDATA)>
    <!ELEMENT special_skill (#PCDATA)>
    <!ATTLIST animal name CDATA #REQUIRED >
    <!ATTLIST weight unit CDATA "kg">
]>
<animals>
    <animal name="cow">
        <skin>
            Straight fur
        </skin>
        <noise>
            Moo!
        </noise>
        <eyes>
            2
        </eyes>
        <diet>
            Herbivore
        </diet>
        <class>
            Mammalia
        </class>
        <weight unit="kg">
            635-1134
        </weight>
        <special_skill>
            Chewing
        </special_skill>
    </animal>

    <animal name="sheep">
        ...
    </animal>

</animals>

I was looking for how to replace the DTD validation with an XSD but couldn't find any examples. It seems like XSDs always need to be defined in a separate file and the be referenced by the XML. Is this true that XSD cannot be used internally?


回答1:


In principle you can do:

<package>
  <xs:schema id="XSD">
   ... schema goes here ...
  </xs:schema>
  <doc xsi:noNamespaceSchemaLocation="#XSD">
   ... instance goes here ...
  </doc>
</package>

But (a) there's no guarantee that any particular schema processor will support this form of location URI, and (b) it's hard to see the point.

I know it's done with DTDs, but I've never really understood:

(i) if you want to validate a document, surely you want to know what schema it's valid against, rather than trusting it to define its own? What use is it to know "this document is valid against some schema but I've no idea what's in that schema"?

(ii) when did you ever have a schema that described only a single instance document? Schemas by their nature define classes of document, and those classes are rarely singletons.




回答2:


No, although you may find some ad hoc implementational support for embedding an XSD within an XML document instance, there is no standard mechanism for XSD that corresponds to DTD's internal subset.



来源:https://stackoverflow.com/questions/39336531/is-it-possible-to-use-xml-schemas-internally-just-like-dtds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!