代码之家  ›  专栏  ›  技术社区  ›  victorio

使用targetNamespace分离复杂类型的XSD

  •  0
  • victorio  · 技术社区  · 7 年前

    我编写了一个非常简单的XML:

    <?xml version="1.0" encoding="utf-8"?>
    <something attribute1="21" attribute2="23">
      <newelement code="code1"/>
    </something>
    

    我想写一个XSD来验证这个XML,它工作得非常好:

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
        <xs:element name="something">
            <xs:complexType>
                <xs:sequence>
                    <xs:element minOccurs="0" name="newelement" nillable="true">
                        <xs:complexType>
                            <xs:attribute type="xs:string" name="code"/>
                        </xs:complexType>
                    </xs:element>
                </xs:sequence>
                <xs:attribute name="attribute1" type="xs:int"/>
                <xs:attribute name="attribute2" type="xs:int"/>
            </xs:complexType>
        </xs:element>
    </xs:schema>
    

    分离的复杂类型 ,因为例如,如果我需要与 newelement

    <?xml version="1.0" encoding="utf-8"?>
    <xs:schema targetNamespace="my-common-types"
               xmlns:xs="http://www.w3.org/2001/XMLSchema"
               xmlns:tns="my-common-types">
        <xs:element name="something">
            <xs:complexType>
                <xs:sequence>
                    <xs:element minOccurs="0" name="newelement" nillable="true" type="tns:ElementWithCode"/>
                </xs:sequence>
                <xs:attribute name="attribute1" type="xs:int"/>
                <xs:attribute name="attribute2" type="xs:int"/>
            </xs:complexType>
        </xs:element>
    
        <xs:complexType name="ElementWithCode">
            <xs:attribute name="code" type="xs:string"/>
        </xs:complexType>
    </xs:schema>
    

    然后,我总是得到这样一个错误:

    错误:元素“something”:没有匹配的全局声明可用

    所以使用 targetNamespace 但我不明白我怎么能让它工作。请给我一些建议。谢谢您!

    2 回复  |  直到 7 年前
        1
  •  1
  •   Michael Kay    7 年前

    重构的模式是针对命名空间“MyCommonTypes”的,而原来的模式是针对没有命名空间的。如果希望元素不在命名空间中,则(全局)元素声明必须在没有命名空间的架构文档中 targetNamespace . 如果需要,您仍然可以将类型声明放在名称空间中,但是它们必须放在单独的模式文档中,该文档使用导入到无名称空间模式文档中 xs:import

        2
  •  0
  •   victorio    7 年前

    XML和XSD中都缺少部分。

    xmlns="my-common-types" <something> 元素。

    XSD错过了 elementFormDefault="qualified" 属性来自 <xs:schema> 元素。