XML模式中的递归?

Mig*_*ero 46 xsd

我需要创建一个XML模式来验证XML文档的树结构.我不确切知道树的出现或深度.

XML示例:

<?xml version="1.0" encoding="utf-8"?>
<node>
  <attribute/>
  <node>
    <attribute/>
    <node/>      
  </node>
</node> 
Run Code Online (Sandbox Code Playgroud)

哪种验证方法最好?递归?

小智 66

如果你需要一个递归类型声明,这里有一个可能有用的例子:

<xs:schema id="XMLSchema1"
    targetNamespace="http://tempuri.org/XMLSchema1.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/XMLSchema1.xsd"
    xmlns:mstns="http://tempuri.org/XMLSchema1.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:element name="node" type="nodeType"></xs:element>

  <xs:complexType name="nodeType">    
    <xs:sequence minOccurs="0" maxOccurs="unbounded">
      <xs:element name="node" type="nodeType"></xs:element>
    </xs:sequence>
  </xs:complexType>

</xs:schema>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这定义了一个递归模式,只有一个名为"node"的节点可以根据需要进行深入.


Mic*_*own 41

XSD确实允许元素的递归.这是给你的样品

<xsd:element name="section">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element ref="title"/>
      <xsd:element ref="para" maxOccurs="unbounded"/>
      <xsd:element ref="section" minOccurs="0" maxOccurs="unbounded"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>
Run Code Online (Sandbox Code Playgroud)

如您所见,section元素包含一个section类型的子元素.

  • +1我相信这是一个比接受的更好的解决方案,因为它允许递归元素是ComplexType. (9认同)
  • 也许知道你可以只在全局元素上使用ref属性是有用的,如下所示:http://stackoverflow.com/questions/13073265/i-have-error-in-xml-the-element-is-not -declared的XML错误 (3认同)