Declaring an attribute for a different namespace in XML Schema

喜夏-厌秋 提交于 2019-12-10 04:04:19

问题


I've been using an XML format that is a mix of different existing formats and some custom elements and attributes, and I thought I should write a schema for those custom bits.

One thing I do is use custom attributes on elements in existing formats, like this:

<ns1:something attA="b" attB="a" ns2:extraAtt="c"/>

I understand that doing this is allowed but I cannot think how to declare my "extraAtt" in XML Schema or, worse, in a DTD.

I have tried reading the specification, but it could just as well be written in Chinese as far as I am concerned. Most tutorials talk only about "name", "type", and "use", e.g. this one and that one.


回答1:


Each schema document defines components (pieces of a schema) for one namespace. So to define your attribute ns2:extraAtt you want a schema document something like this one:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  targetNamespace="http://example.com/my-ns2">
  <xs:attribute name="extraAtt" type="xs:anySimpleType"/>
</xs:schema>

The declaration of element ns1:something will need to allow for this attribute somehow, either with an attribute reference (<xs:attribute ref="ns2:extraAtt"/>) or with an attribute wildcard (<xs:anyAttribute namespace="http://example.com/my-ns2"/> or similar).


Sorry about the legibility of the spec; it's a long story, but essentially some members of the WG did not think people like you exist ("no one except implementors reads the spec, and as long as they don't complain it's readable enough" -- at least, that was what they said before some implementors did complain, loudly and bitterly; then they just changed the subject).




回答2:


To declare just the attribute you can use this XSD:

<xs:schema 
  targetNamespace="theNamespaceUri"
  elementFormDefault="qualified"
  attributeFormDefault="qualified"
  xmlns="theNamespaceUri"
  xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:attribute name="extraAtt" type="xs:string">
  </xs:attribute>

</xs:schema>

(assuming extraAtt is a simple string - you can use any type, or restrict an existing type etc.)



来源:https://stackoverflow.com/questions/18598558/declaring-an-attribute-for-a-different-namespace-in-xml-schema

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