[Newbie] One XPath expression for inline and referenced elements

R

Rach

Hi,

I'd like to model the following using schema definition (XSD) and I'd like
to express paths using (XPath).

1. Is it possible to define a xsd for rootBook? As you can see, a <rootBook>
can contain inline <chapter> definition and references to a loose <chapter>
outside of <rootBook>.

<rootBook>
<chapter id="1">
<paragraph>Para 1</paragraph>
<paragraph>Para 2</paragraph>
<paragraph>Para 3</paragraph>
</chapter>
<chapter ref="2"/>
</rootBook>

<chapter id="2">
<paragraph>Para 4</paragraph>
<paragraph>Para 5</paragraph>
<paragraph>Para 6</paragraph>
</chapter>

2. And then how do I define "one" XPath expression that caters for both
inline and external chapters?

expression: //rootBook/chapter[@id="1"]/*
returns:
/rootBook[1]/chapter[1]/paragraph[1] - Para 1
/rootBook[1]/chapter[1]/paragraph[2] - Para 2
/rootBook[1]/chapter[1]/paragraph[3] - Para 3

I want this expression to return me the following to, when the queried id is
"2":
/rootBook[1]/chapter[2]/paragraph[1] - Para 4
/rootBook[1]/chapter[2]/paragraph[2] - Para 5
/rootBook[1]/chapter[2]/paragraph[3] - Para 6

Many thanks.

-rach
 
A

Andy Dingley

Rach said:
2. And then how do I define "one" XPath expression that caters for both
inline and external chapters?

You don't? :cool: As anyone who has tried to manipulate RDF through
XSLT can tell you, this is a painful process. Actually for your
example it should work fine - but it gets _very_ tiresome for RDF.

The trick is to use
<xsl:key name="ext-chapters" match="/chapter" use="@id" />

Then reference them via the id value, using the ref attribute of the
referring chapter


As originally stated, your example is trivial. If you already have the
id value, then just locate them with //chapter [@id = $id-requested]

However I think what you're really after is how to process a set of
chapters and find their content, transparently whether they're in-line
or referenced. So give this a try


<xsl:key name="ext-chapters" match="//chapter" use="@id" />

<xsl:template name="output-chapter" >
<xsl:param name="chapter" select="/.." />
<xsl:apply-templates select="$chapter [@id] /* |
key('ext-chapters', $chapter/@ref )/* " />
</xsl:template>


<xsl:template name="iterate-chapters" >
<xsl:for-each select="//rootBook/chapter " >
<xsl:call-template name="output-chapter" >
<xsl:with-param name="chapter" select="." />
</xsl:call-template>
</xsl:for-each>
</xsl:template>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top