取决于属性/元素值的不同子元素 [英] Different sub-elements depending on attribute/element value

查看:107
本文介绍了取决于属性/元素值的不同子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个XSD问题-如何实现以下XML元素均有效:

Another XSD question - how can I achieve that the following XML elements are both valid:

<some-element>
  <type>1</type>
  <a>...</a>
</some-element>

<some-element>
  <type>2</type>
  <b>...</b>
</some-element>

子元素( <a> <b>)应取决于<type>的内容(也可以是属性).这在RelaxNG中是如此简单-但是RelaxNG不支持密钥完整性:(

The sub-elements (either <a> or <b>) should depend on the content of <type> (could also be an attribute). It would be so simple in RelaxNG - but RelaxNG doesn't support key integrity :(

有没有一种方法可以在XSD中实现呢?

Is there a way to implement this in XSD?

注意:XML模式版本1.1支持<xs:alternative>,这可能是一个解决方案,但是afaik还没有引用实现(例如libxml2)支持此功能.因此,我正在寻找解决方法.我想出的唯一方法是:

Note: XML schema version 1.1 supports <xs:alternative>, which might be a solution, but afaik no reference implementation (e.g. libxml2) supports this yet. So I'm searching for workarounds. The only way I've come up with is:

<type>1</type>
<some-element type="1">
    <!-- simple <xs:choice> between <a> and <b> goes here -->
    <a>...</a>
</some-element>
<!-- and now create a keyref between <type> and @type -->

推荐答案

最好的解决方案是删除<type/>元素,并且对于<a/><b/>仅具有xs:choice,并让应用程序使用xml整理类型.

The best solution is to remove the <type/> element and only have a xs:choice for <a/> and <b/> and let the application consuming the xml sort out the type.

另一种解决方案可能是让<a/><b/>xs:choice使用xslt脚本来验证与<a/><b/>相关的<type/>元素.

Another solution might be to have a xs:choice for <a/> and <b/> use an xslt script to do a validation of the <type/> element in relation to <a/> and <b/>.

首先针对xmlschema验证xml,然后使用xslt对其进行转换,如果转换的结果为空字符串,则为有效,否则将结果字符串显示为错误消息.

First validate the xml against the xmlschema then use the xslt to do a transformation on it, if the result of the transform is empty string it is valid otherwise show the resulting string as an error message.

类似这样的事情...

Something like this...

XmlSchema:

  <xs:element name="some-element">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="type" type="xs:integer" />
        <xs:choice>
          <xs:element name="a" type="xs:string" />
          <xs:element name="b" type="xs:string" />
        </xs:choice>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Xslt:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:demo="uri:demo:namespace">
  <xsl:output method="text" />
  <xsl:template match="/demo:some-element">
    <xsl:if test="type = 1 and not(demo:a)">
      When type equals 1 element a is requred.
    </xsl:if>
    <xsl:if test="type = 2 and not(demo:b)">
      When type equals 2 element b is requred.
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

这篇关于取决于属性/元素值的不同子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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