2017-04-07 56 views
0

我有一个文档需要一些标题具有标准名称,而另一些则由作者提供。为了区分差异,我创建了一个属性“hardTitle”。如果hardTitle属性有一个值,则标题元素应该显示hardTitle的值并锁定它不被编辑。如果hardTitle属性为空,那么作者可以使用他们喜欢的任何标题。将属性值分配给XML中的元素内容(使用XSD或XSL)

我试过使用枚举值(下面的代码),但那只会告诉我,如果值不正确 - 它不会填充元素中的值,也不会锁定元素内容被编辑。

我想什么:

<chapter> 
    <title hardTitle="Scope">Scope</title> [auto-populated from hardTitle and locked] 
    ... 
    <title>This Title Can Be Anything</title> 
    ... 
    <title hardTitle="NewT">NewT</title> [auto-populated from hardTitle and locked] 
</chapter> 

这里是我到目前为止的代码。我知道xs:restriction将文本限制为枚举值...但是我正在寻找一些将强制基于属性的内容并将其从编辑中锁定的内容。

.xsd文件片段:

<xs:element name="title" type="editableTitle"> 
     <xs:alternative test="if(@hardTitle)" type="lockedTitle" /> 
    </xs:element> 

    <xs:complexType name="editableTitle"> 
     <xs:simpleContent> 
      <xs:extension base="xs:string"> 
       <xs:attribute name="hardTitle" /> 
      </xs:extension> 
     </xs:simpleContent> 
    </xs:complexType> 

    <xs:complexType name="lockedTitle"> 
     <xs:simpleContent> 
      <xs:restriction base="editableTitle"> 
       <xs:simpleType> 
        <xs:restriction base="xs:string"> 
         <xs:enumeration value="@hardTitle" /> 
        </xs:restriction> 
       </xs:simpleType> 
      </xs:restriction> 
     </xs:simpleContent> 
    </xs:complexType> 
+1

XSD真的不支持“锁定“,它会告诉你它是否”无效“。您可能需要针对属性之间的这种逻辑进行应用程序编程。 –

+0

XSD也不支持修改文档。 –

+0

感谢您花时间回答我的问题。我刚刚开始使用XML,这已经为我清楚了解我可以做什么以及不能做什么用XSD。 –

回答

0

你的约束可以应用,其中即满足约束条件的输入文档转换为不同文件的意义,通过这个简单的XSL转换:

<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

    <xsl:template match="node()|@*"> 
    <xsl:copy> 
     <xsl:apply-templates select="node()|@*" /> 
    </xsl:copy> 
    </xsl:template> 

    <xsl:template match="title[@hardTitle]"> 
    <xsl:copy> 
     <!-- supposes that <title> elements will not have child elements --> 
     <xsl:apply-templates select="@*" /> 
     <xsl:value-of select="@hardTitle" /> 
    </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet> 
0

你的约束可以通过XSD 1.1断言上title表示,

<xs:assert test="not(@hardTitle) or . = @hardTitle"/> 

它说,有必须是没有@hardTitle属性或字符串值title必须等于@hardTitle的值。

您的约束无法在XSD 1.0中表达。

+0

感谢您抽出宝贵时间来回答我的问题。我能够使用assert来测试值并阻止文件验证 - 但我需要更进一步,并尝试将该属性的值应用到元素本身。 –