XSD requiring a specific root element exist in an XML document?

余生长醉 提交于 2021-01-28 03:35:03

问题


I want to validate a XML file and to make sure it has a root element called speak like this:

<speak>
  <!--other node here...-->
</speak>

the speak element must exist in XML and must appears only once. I try to add code below in my XSD file:

<xsd:element name="speak" type="speak" minOccurs="1" maxOccurs="1"/>

But it does not work.


回答1:


In the schema itself, you can't put a constraint on what the root element must be. (That's by design, though not everyone thinks it's a good design.) Any global element declaration can match the root element.

Some APIs for invoking validation may allow you to constrain the root element. For example, if you use the Saxon schema validator and run it from the command line, you can specify -top:speak to require that the top-level element is named speak.




回答2:


XSD occurrence constraints are not allowed on root elements because XML documents are already constrained to consist of a single root element. Therefore, simply specify a single global element declaration, and make declaration be for the required root element in your XML. It will effectively be minOccurs="1" maxOccurs="1" anyway then.




回答3:


You can use minOccurs/maxOccurs on the sequence element, like the following:

 <xs:element name="speak">
     <xs:complexType>
         <xs:sequence minOccurs="1" maxOccurs="1">
             ...
         </xs:sequence>
     </xs:complexType>
 </xs:element>

but it is not necessary, as it is a redundant default attribute value assignment.



来源:https://stackoverflow.com/questions/55014034/xsd-requiring-a-specific-root-element-exist-in-an-xml-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!