p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   XSLT (http://p2p.wrox.com/forumdisplay.php?f=86)
-   -   XSL newbie question (http://p2p.wrox.com/showthread.php?t=48819)

Someone2006 October 9th, 2006 09:13 PM

XSL newbie question
 
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.



joefawcett October 10th, 2006 02:22 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:
Code:

/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)

mhkay October 10th, 2006 03:06 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

Someone2006 October 10th, 2006 07:10 AM

Hi,

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

-S.


mhkay October 10th, 2006 07:20 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


All times are GMT -4. The time now is 09:51 AM.

Powered by vBulletin®
Copyright ©2000 - 2019, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.