2011-09-02 105 views
2

我想创建一个只允许一个单一根节点的xml模式。如何避免在XML模式中使用全局元素

在根节点下面的结构中,有一个要在不同位置重用的元素。

我的第一种方法是在模式中创建一个全局元素,但是如果我这样做了,只有一个标记为根的xml文档对这个模式也是有效的。

如何创建仅允许用作我的根结构内的ref-element的全局元素?

这就是我想有:

<root> 
    <branch> 
    <leaf/> 
    </branch> 
    <branch> 
    <fork> 
     <branch> 
      <leaf/> 
     </branch> 
     </leaf> 
    </fork> 
</root> 

但是,这也将是有效的 <leaf/>作为根节点

回答

0

XML始终只有一个根节点。它代表了一种等级结构,并且与其模式绑定在一起。所以你不能改变具有相同模式和有效的根元素。

首先,应充分形成这样的:

<?xml version="1.0" encoding="UTF-8"?> 

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-scheme.xsd> 
    <branch> 
     <leaf/> 
    </branch> 
    <branch> 
     <fork> 
      <branch> 
       <leaf/> 
      </branch> 
      <leaf/> 
     </fork> 
    </branch> 
</root> 

我建议的方案是这样的:

<?xml version="1.0" encoding="UTF-8"?> 
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> 
    <xs:complexType name="root"> 
     <xs:sequence> 
      <xs:element ref="branch" minOccurs="0" maxOccurs="unbounded"/> 
     </xs:sequence> 
    </xs:complexType> 
    <xs:complexType name="branch"> 
     <xs:choice> 
      <xs:element ref="fork" minOccurs="0" maxOccurs="unbounded"/> 
      <xs:element ref="leaf" minOccurs="0" maxOccurs="unbounded"/> 
     </xs:choice> 
    </xs:complexType> 
    <xs:complexType name="fork"> 
     <xs:sequence> 
      <xs:element ref="branch" minOccurs="0" maxOccurs="unbounded"/> 
      <xs:element ref="leaf" minOccurs="0" maxOccurs="unbounded"/> 
     </xs:sequence> 
    </xs:complexType> 
    <xs:complexType name="leaf"/> 
    <xs:element name="root" type="root"/> 
    <xs:element name="branch" type="branch"/> 
    <xs:element name="fork" type="fork"/> 
    <xs:element name="leaf" type="leaf"/> 
</xs:schema> 

我希望它可以帮助你。

+0

好吧,但是什么阻止我只使用叶标记作为XML数据的单个内容? – martin

相关问题