通过 XSD 验证未知 XML 元素的后代? [英] Validate descendants of unknown XML elements via XSD?
问题描述
我的 XML 文件看起来像:
My XML file looks like :
<root>
<template>
<unknownTag>
<anotherUnknownTag/>
<anotherKnownTag/>
<field name='price'/>
</unknownTag>
</template>
<template>
<field name='salary'/>
</template>
<anothorKnownTag/>
</root>
我想对标签<field/>
的属性name
应用正则表达式限制,无论它是孩子还是孙子还是孙子等等.我尝试了以下代码,但正则表达式仅适用于元素字段,当它是 template
标记的直接子元素时.
I want to apply regex restriction to the attribute name
of the tag <field/>
whether it's a child or a grandchild or a grand grandchild and so on.
I have tried the following code, but the regex only applied to the element field when it's a direct child of the template
tag.
<xs:element name="template">
<xs:complexType>
<xs:complexContent>
<xs:sequence>
<xs:element name="field">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[a-z][a-z_]*"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:any processContents="lax"/>
</xs:sequence>
</xs:complexType>
</xs:element>
推荐答案
您实际上可以在 XSD 1.0 中表达所请求的约束:
You can actually express the requested constraints in XSD 1.0:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:any processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="field">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="name">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[a-z][a-z_]*"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:schema>
注意:您甚至可以将root
简化为
<xs:element name="root"/>
但较长的形式不那么神秘.
but the longer form is less cryptic.
<?xml version="1.0" encoding="UTF-8"?>
<root>
<template>
<unknownTag>
<anotherUnknownTag/>
<anotherKnownTag/>
<field name="price"/>
</unknownTag>
</template>
<template>
<field name="salary"/>
</template>
<anothorKnownTag/>
</root>
无效的 XML
由于 field/@name
值与正则表达式不匹配,以下 XML 有两个有效性错误:
Invalid XML
The following XML has two validity errors due to field/@name
values not matching the regex:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<template>
<unknownTag>
<anotherUnknownTag/>
<anotherKnownTag/>
<field name="price999"/>
</unknownTag>
</template>
<template>
<field name="big salary"/>
</template>
<anothorKnownTag/>
</root>
这篇关于通过 XSD 验证未知 XML 元素的后代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!