开发者

How to write an XSLT to transform following XML in the following HTML?

开发者 https://www.devze.com 2022-12-25 04:43 出处:网络
<result> <binding name=\"PropertyURI\"> <uri>http://dbpedia.org/ontology/motto</uri>
<result>  
   <binding name="PropertyURI">
      <uri>http://dbpedia.org/ontology/motto</uri>
   </binding> 
   <binding name="Property">
      <literal xml:lang="en">motto</literal>
   </binding>
   <binding name="ValueURI">
      <uri>http://dbpedia.org/ontology/motto</uri>
   </binding>
   <binding name="Value">
      <literal>Ittehad, Tanzim, Yaqeen-e-Muhkam(Urdu)</literal>
   </binding>
</result>

I want to transform it like

<a href=PropertyURI>Property</a>
<a href=ValueURI>Value</a>

Problem is that number of binding tags can different. Sometimes we may have only URIs or ony Values.

How can I know in XSLT tha开发者_如何学Ct if binding with @name=PropertyURI is available?

If yes then what is the name of next binding @name attribute?


There is already an answer that seems valid but I've just spent 10 minutes testing the following code so :

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

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

<xsl:template match="/">
  <xsl:apply-templates select="/result/binding[@name='PropertyURI']"/>
</xsl:template>
  <xsl:template match="binding">
    <a>
      <xsl:attribute name="href">
        <xsl:value-of select="./uri"/>
      </xsl:attribute>
      <xsl:value-of select="./following-sibling::binding[1][@name='Property']/literal"/>
    </a>
  </xsl:template>
</xsl:stylesheet> 


It's not quite clear what you're looking for, since your description of the problem and your desired output don't seem to be related. I think that what you want to do is find every binding element with a uri child, find the related binding element that has a literal child, and use the uri and literal values to populate an a element.

This template assumes that the two binding elements are related because the name attribute on the one with the uri child starts with the name attribute on the one with the literal child, e.g. "PropertyURI" starts with "Property" and "ValueURI" starts with "Value":

<xsl:template match="binding[uri]">
   <xsl:variable name="name" value="@name"/>
   <xsl:variable name="literal" 
                select="/result/binding[starts-with($name, @name)]/literal"/>
   <xsl:if test="$literal">
      <a href="{uri}">
         <xsl:value-of select="$literal"/>
      </a>
   </xsl:if>
</xsl:template>

If the related element is simply the next binding element after the one with the uri child, use the above template, replacing the variable assignment with:

<xsl:variable name="literal" select="following-sibling::binding[1]/literal"/>
0

精彩评论

暂无评论...
验证码 换一张
取 消