3

我目前正在学习 XML,并且已经了解了与多个名称空间一起使用的 XML Schema 的奇妙世界。

我的问题是我应该何时不必声明命名空间前缀。

考虑以下 XML 模式片段:

<A:schema   xmlns:A="http://www.w3.org/2001/XMLSchema" 
        targetNamespace="B" 
        xmlns:B="B" 
        elementFormDefault="qualified">

    <A:element name="foo">
        <complexType>                   <!-- or A:complexType?-->
            <element name="bar" type="B:myType"/>       <!-- or A:element?-->
        </complexType>
    </A:element>

    <B:complexType name="myType">
        <choice>                         <!--or B:choice?-->
            <element name="baz" type="string"/>      <!--or B:element?-->
            <element name="bas" type="string"/>      <!--or B:element?-->
        </choice>
    </B:complexType>

</A:schema>

我是否必须在具有命名空间前缀的节点的所有子节点上指定命名空间前缀,或者这是继承的?或者A:complexTypecomplexType它的父节点附加了 A 命名空间前缀时不同?

4

1 回答 1

4

前缀与命名空间 URI的绑定由子元素继承,但元素本身不会自动放置在与其父元素相同的命名空间中。如果它们是,将无法用不在命名空间中的子元素来表达命名空间中的元素。在您的示例中,作为架构定义一部分的所有元素都需要位于http://www.w3.org/2001/XMLSchema命名空间中(通常映射到xsdorxs前缀):

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

    <xs:element name="foo">
        <xs:complexType>
            <xs:element name="bar" type="B:myType"/>
        </xs:complexType>
    </xs:element>

    <xs:complexType name="myType">
        <xs:choice>
            <xs:element name="baz" type="xs:string"/>
            <xs:element name="bas" type="xs:string"/>
        </xs:choice>
    </xs:complexType>

</xs:schema>

例外情况是当您使用xmlns="..."which 为没有前缀的元素定义默认命名空间时,例如

<schema xmlns="http://www.w3.org/2001/XMLSchema" ...>
   <element ...>
      <complexType ...>

相当于

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" ...>
   <xs:element ...>
      <xs:complexType ...>

type="B:myType"是正确的,因为它指的是架构中命名的类型,myTypetargetNamespace您又将其映射到前缀B

于 2012-10-10T12:30:58.130 回答