根据一个属性值进行 XSD 类型验证
我记得,不久前我有一段类似的 XML:
<item type="Person" name="Pawel" Surname="Wu" />
<item type="Address" city="Sample town" address="Sample street etc." />
并且我想用 XSD 来验证它。然而,上次我这样做时(大约两年前我有这样一个任务)不可能根据属性值指定元素类型(在本例中是type)。所以我被迫将 XML 结构重新设计成这样:
<person name=..... />
<address city=..... />
编写 XSD 是小菜一碟。
今天,我有类似的问题。作为输入,我获得带有通用 item 元素的 XML 文档,这些元素具有 type 属性,而后者,根据此属性值,是否允许/需要其他属性。该形状的文档仍然是在系统中手动创建的,因此我希望有一个可以减少/消除错误的 XSD 文档(很容易忘记带有 type="personalDetails" 的元素 item 必须具有特定的属性集合)。
现在是否可以编写 XSD 模式来验证此类文档?
谢谢,帕维尔
As I remember, some time ago I had similar piece of XML:
<item type="Person" name="Pawel" Surname="Wu" />
<item type="Address" city="Sample town" address="Sample street etc." />
and I wantetd to validate it with XSD. However, last time I did it (about 2 years ago I had such a task) it was impossible to specify element type according to attribute value (type in this example). So I was forced to redesign XML structure into something like this:
<person name=..... />
<address city=..... />
and writing XSD was piece of cake.
Today, I have similar issue. As an input I get XML document with generic item elements that have type attriibute, and latter, depending on this attribute value, another attributes are allowed/required or not. Documents in that shape are still created in system manually, so I would like to have an XSD document that will reduce/eliminate errors (it's easy to forget that element item with type="personalDetails" must have a particular collection of attributes set).
Is it possible to write a XSD schema to validate such a documents now?
Thanks,Pawel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法根据属性值进行验证。但是,您可以使用
xsi:type
指定 XML 实例中元素的类型。 点击,点击。You can't validate based on the attributevalue. However, you can use
xsi:type
to specify the type of the element in the XML instance. Click, click.您可以使用 XSD 1.1 来完成此操作,目前已在 Xerces 和 Saxon 中实现(即尚未广泛实现)。
处理此类通用词汇表验证的一种方法是在验证之前对其进行转换,即。将23
转换为You can do this with XSD 1.1, currently implemented in Xerces and Saxon (i.e. not yet very widely).
One way to handle validation of a generic vocabulary like this is to transform it prior to validation, ie. convert
<attribute name="size" value="23">
to<size>23</size>