【问题标题】:extending XML with unknown elements使用未知元素扩展 XML
【发布时间】:2010-12-12 09:10:58
【问题描述】:

假设我有一个 XML 模式并希望在多个节点上支持一些扩展。扩展应该是这些节点中的有效 XML。

我知道这可以通过架构中的 元素来实现。但是,在使用我的架构的 XML 中,我希望此扩展仅使用来自其他 XSD 的节点。因此,在运行时指定扩展的架构,然后能够根据扩展架构验证此扩展。

以下示例使用静态扩展架构:


<xs:element name="notes" minOccurs="0">
  <xs:complexType>
    <xs:sequence>
      <xs:any namespace="http://www.w3.org/1999/xhtml"
           minOccurs="0" maxOccurs="unbounded"
           processContents="skip"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

现在我想在我的 XML 中指定这个模式,例如(我是新手),像这样:


<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:noNamespaceSchemaLocation="myschema.xsd">
  <bar>
    <extension>
       <html namespace="http://www.w3.org/1999/xhtml">
         <body>Hello, World!</body>
       </html>
    </extension>
  </bar>
</foo>

对此最好的方法是什么?理想情况下,我想在我的 XML 扩展节点中使用架构的 XML 列表。

谢谢!

== 已编辑,更详细的解释:==

我想在特定节点内支持用户定义的 XML 数据。在编写“主”架构时,我不知道这些扩展的架构。

我在我的 XSD 中指定了以下片段:


<xs:element name="extension">
    <xs:complexType>
        <xs:sequence>
            <xs:any namespace="##other" processContents="strict"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

并想使用以下 XML:


<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="test.xsd" >
    <bar>
        <extension>
            <html xmlns="http://www.w3.org/1999/xhtml">
                <body2>Hello, world!</body2>
            </html>
        </extension>
    </bar>
</foo>

现在我确实想要一个解析器错误,因为 元素无效。

【问题讨论】:

  • 我看不到错误! XMLSpy 可能很愚蠢,不会切换名称空间。然而...... body2 在这一点上是一个无效元素!如果你拿身体怎么办?
  • 查看我的编辑。 XMLSpy 拒绝 html 元素是正确的:您没有指定从哪里获取它的架构。

标签: xml xsd


【解决方案1】:

使用“严格”处理来强制任何元素的内容根据其架构进行验证,即

<xs:element name="notes" minOccurs="0">
  <xs:complexType>
    <xs:sequence>
      <xs:any namespace="http://www.w3.org/1999/xhtml"
           minOccurs="0" maxOccurs="unbounded"
           processContents="strict"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

您的文档验证应该会失败,因为处理器可能无法获得 XHTML 的模式。您还需要在实例文档中指定这一点,如下所示:

<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:noNamespaceSchemaLocation="test.xsd">
 <extension>
  <html xmlns="http://www.w3.org/1999/xhtml" 
    xsi:schemaLocation="http://www.w3.org/1999/xhtml 
                        http://www.w3.org/2002/08/xhtml/xhtml1-strict.xsd">
   <body2>Hello, world!</body2>
  </html>
 </extension>
</foo>

现在,许多 XSD 验证器仍然会对此感到窒息,因为他们不考虑 html 元素上的 schemaLocation 属性(尽管根据规范他们应该这样做)。 将 schemaLocation 属性移动到根元素可能(也可能不会) 改进:如果验证器抱怨 html 元素,它就坏了。

【讨论】:

  • 谢谢马丁。也许我的问题不够清楚(或者我不明白答案)。我的意思是,我不知道我的“主”模式中的扩展模式,所以我不能像在第一个片段中那样静态定义该模式。请参阅我在开始主题中的补充。再次感谢!
  • 太棒了!是的,我现在明白出了什么问题。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2019-04-27
  • 2011-12-09
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
  • 2016-06-26
  • 2011-11-22
相关资源
最近更新 更多