XML模式,如何确保一个元素存在具有特定属性值 [英] Xml schema, how to make sure one element exists with a specific attribute value

查看:17
本文介绍了XML模式,如何确保一个元素存在具有特定属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何强制在 XML 中存在具有特定属性值的元素?

How do I enforce the existing of an element with a specific attribute value in the XML?

例如:

<events>
  <event type="system" desc="this is a system event"/>
  <event type="bla1" desc="this is bla1 event"/>
  <event type="bla2" desc="this is bla2 event"/>
</events>

我需要一个规则来确保 type 属性 = 'system' 的事件元素存在(一次).所有其他事件元素都是可选的;

I need a rule to make sure the event element with type attribute = 'system' exists (once). All other event elements are optional;

推荐答案

如果你使用的是 XML Schema 1.0,你不能直接表达约束.您可以通过 Schematron 或 XSLT 在 XML Schema 1.0 之外直接进行.

If you're using XML Schema 1.0, you cannot express the constraint directly. You could do it outside of XML Schema 1.0 via Schematron or XSLT directly.

如果您使用的是 XML Schema 1.1,您可以通过 xs:assert 指定共现约束:

If you're using XML Schema 1.1, you can specify co-occurrence constraints via xs:assert:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           version="1.0">
  <xs:element name="events">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="event" minOccurs="1" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="type" type="xs:string"/>
            <xs:attribute name="desc" type="xs:string"/>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
      <xs:assert test="count(event[@type = 'system']) = 1"/>
    </xs:complexType>
  </xs:element>
</xs:schema>

这篇关于XML模式,如何确保一个元素存在具有特定属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆