Unable to get the XSLT select id() function to work successfully

守給你的承諾、 提交于 2019-12-25 10:02:37

问题


I'm having trouble getting the id() function to work in my xslt transformation per the example code below and I'm not sure why. When I load data.xml into a browser I'm expecting to see just the name & size values of the 'BC' item per the stylesheet/transformation. Any suggestions? FYI: I've adapted the example from another site.

File: transform.xslt

<?xml version="1.0" encoding="UTF-8"?>

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

<xsl:output method="html" indent="yes" encoding="UTF-8" />

<xsl:template match="/">
    <html>
        <body>      
            <xsl:value-of select="id('BC')/name" />
            <xsl:value-of select="id('BC')/size" />             
        </body>
    </html>
</xsl:template>

File: data.xml

<?xml version="1.0" encoding="UTF-8"?>

<?xml-stylesheet type="text/xsl" href="transform.xslt" ?>

<provinces xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="data.xsd">
 <province id="AB">
  <name>Alberta</name>
  <size>33</size>
 </province>
<province id="BC">
 <name>British Columbia</name>
 <size>44</size>
</province>
<province id="MB">
 <name>Manitoba</name>
 <size>55</size>
 </province>
</provinces>

File: data.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="provinces">   
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="province" minOccurs="1" maxOccurs="unbounded" />
        </xs:sequence>
    </xs:complexType>       
</xs:element>

<xs:element name="province">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="name"  />
            <xs:element name="size" />  
        </xs:sequence>
    <xs:attribute name="id" type="xs:ID" use="required"/>
    </xs:complexType>
</xs:element>       

 </xs:schema>

回答1:


Just because the attribute is named id doesn't make it an ID attribute: it has to be declared as an ID in the DTD or schema (or it can be named xml:id if the processor supports that).

It's probably simplest here to switch to using key() instead.




回答2:


As XSL 2.0 uses the same functions as XQuery 1.0 / XPath 2.0, you can also use the function fn:element-with-id. This function solves the problem that fn:id(...) only works with xml:id attributes (and not with xs:ID).

Read more about this here: How to use the XQuery fn:id() function?.




回答3:


Try

<xsl:value-of select="/id('BC')/name" />

instead of

<xsl:value-of select="id('BC')/name" />


来源:https://stackoverflow.com/questions/9264339/unable-to-get-the-xslt-select-id-function-to-work-successfully

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!