代码之家  ›  专栏  ›  技术社区  ›  Rahel Lüthy

XML架构:导入共享元素时出现命名空间问题

  •  0
  • Rahel Lüthy  · 技术社区  · 15 年前

    当尝试从XML模式导入共享定义时,我可以正确地引用共享类型,但是引用共享元素会导致验证错误。

    这是导入共享定义(example.xsd)的架构:

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema
      elementFormDefault="qualified"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      xmlns:shared="http://shared.com">
    
        <xs:import namespace="http://shared.com" schemaLocation="shared.xsd"/>
    
        <xs:element name="example">
            <xs:complexType>
                <xs:sequence>
                    <xs:element ref="importedElement"/>
                    <xs:element ref="importedType"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    
        <xs:element name="importedElement">
            <xs:complexType>
                <xs:sequence>
                    <xs:element ref="shared:fooElement"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    
        <xs:element name="importedType">
            <xs:complexType>
                <xs:sequence>
                    <xs:element name="bar" type="shared:barType"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
    
    </xs:schema>
    

    这些是共享定义(shared.xsd):

    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema
        xmlns:xs="http://www.w3.org/2001/XMLSchema"
        xmlns="http://shared.com"
        targetNamespace="http://shared.com">
    
        <xs:element name="fooElement">
            <xs:simpleType>
                <xs:restriction base="xs:integer"/>
            </xs:simpleType>
        </xs:element>
    
        <xs:simpleType name="barType">
            <xs:restriction base="xs:integer"/>
        </xs:simpleType>
    
    </xs:schema>
    

    现在考虑这个XML实例:

    <?xml version="1.0"?>
    <example
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"                     
      xsi:noNamespaceSchemaLocation="example.xsd">
        <importedElement>
            <fooElement>42</fooElement>
        </importedElement>
        <importedType>
            <bar>42</bar>
        </importedType>
    </example>
    

    验证后,“importedType”工作正常,但“importedElement”出现以下错误:

    从元素“fooelement”开始发现无效内容。“{”之一 http://shared.com 应为“:fooelement”

    我猜想我的问题与名称空间问题有关(因此,不知何故误导性的“got fooelement but was expecting fooelement”)——这里有什么问题的提示吗?

    1 回复  |  直到 15 年前
        1
  •  0
  •   xcut    15 年前

    您正在引用 fooElement 就像它不在命名空间中一样,您需要在实例文档中使用正确的命名空间:

    <?xml version="1.0"?>
    <example
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"                     
      xsi:noNamespaceSchemaLocation="example.xsd" xmlns:shared="http://shared.com">
        <importedElement>
            <shared:fooElement>42</shared:fooElement>
        </importedElement>
        <importedType>
            <bar>42</bar>
        </importedType>
    </example>
    

    编辑: 我应该指出:这就是 类型 元素 ;只有后者出现在文档中(除了一些例外),这就是为什么导入的类型按您的需要工作,而您的元素则不工作。