Subject: XSL newbie question
Posted By: Someone2006 Post Date: 10/9/2006 9:13:18 PM
Hi,

I'm a complete newbie to XSL and I was wondering if someone could help me with my first attempt of this technology.
Here's the XML:

<catalog xmlns="http://www.catalog.org/xml/export-0.3/">
  <dir>
    <id>user:XXX/home</id>
    <text>my text 1</text>
    <foo>zzz</foo>
  </dir>
  
  <dir>
    <id>user:XXX/home/work</id>
    <text>my text 2</text>
    <foo>zzz</foo>
  </dir>
  
  <dir>
    <id>user:YYY/home</id>
    <text>my text 3</text>
    <foo>zzz</foo>
  </dir>
  
  <dir>
    <id>Something completely different</id>
    <text>my text 4</text>
    <foo>zzz</foo>
  </dir>
</catalog>

I'd like to select the <dir> nodes who's <id> is something like "user:*/home". This is the expected output:

<new>
  <dir>
    <id>user:XXX/home</id>
    <text>my text 1</text>
  </dir>
  
  <dir>
    <id>user:YYY/home</id>
    <text>my text 3</text>
  </dir>
</new>

Thanks,
-S.


Reply By: joefawcett Reply Date: 10/10/2006 2:22:30 AM
Assuming you're using version 1.0 then I think you need to combine the starts-with() and substring-after() string functions. So a possible XPath would be:
/ns:catalog/ns:dir[starts-with(ns:id, 'user:') and substring-after(ns:id, '/') = 'home']


You will have to declare the ns prefix as bound to the default namespace. For links on this subject see http://p2p.wrox.com/topic.asp?TOPIC_ID=49630.

--

Joe (Microsoft MVP - XML)
Reply By: mhkay Reply Date: 10/10/2006 3:06:58 AM
XSLT 2.0 supports regular expressions, so you can write

<xsl:template match="catalog">
<new>
  <xsl:copy-of select="dir[matches(id, '^user:.*/work$')]"/>
</new>
</xsl:template>

Your example changes the namespace of all the elements, which the above transformation doesn't attempt: I wasn't sure that was an important part of your requirement or just something that happened by accident.

If you're constrained to use XSLT 1.0 it's a little more difficult because there are no regular expressions and no ends-with() function. You could change the predicate (the expression inside the square brackets) to:

starts-with(id, 'user:') and substring(id, string-length(id)-4) = '/work')

Michael Kay
http://www.saxonica.com/
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference
Reply By: Someone2006 Reply Date: 10/10/2006 7:10:33 AM
Hi,

I'm using Xalan-J and none of this is working :(
Any idea?

-S.

Reply By: mhkay Reply Date: 10/10/2006 7:20:10 AM
If it's not working then you've done something wrong, and to tell you what you've done wrong, we'll need to see what you've done.

Michael Kay
http://www.saxonica.com/
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference

Go to topic 50813

Return to index page 152
Return to index page 151
Return to index page 150
Return to index page 149
Return to index page 148
Return to index page 147
Return to index page 146
Return to index page 145
Return to index page 144
Return to index page 143