2017-04-07 95 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來測試值並阻止文件驗證 - 但我需要更進一步,並嘗試將該屬性的值應用到元素本身。 –