问题描述
我想验证一个 XML 文件并确保它有一个名为 speak
的根元素,如下所示:
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>
speak
元素必须存在于 XML 中并且只能出现一次.我尝试在我的 XSD 文件中添加以下代码:
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"/>
但它不起作用.
推荐答案
在架构本身中,您不能对根元素必须是什么进行约束.(这是设计使然,虽然不是每个人都认为这是一个好的设计.)任何全局元素声明都可以匹配根元素.
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.
一些用于调用验证的 API 可能允许您限制根元素.例如,如果您使用 Saxon 模式验证器并从命令行运行它,您可以指定 -top:speak
以要求顶级元素命名为 speak
.
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
.
这篇关于需要特定根元素的 XSD 是否存在于 XML 文档中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!