selecting a node based on partial names

A

Amit

I have a quick question. Given test XML:

<root>
<ns1:sub>1</ns1:sub>
<ns2:sub>2</ns2:sub>
<ns3:sub>3</ns3:sub>
</root>

is there a way to select all nodes that contain the word "sub". (Due
to namespace constraints, I will be getting the subnodes as <ns1:sub>,
<ns2:sub> and so on.)

regards,
Amit.
 
S

Scott Stearns

Amit said:
I have a quick question. Given test XML:

<root>
<ns1:sub>1</ns1:sub>
<ns2:sub>2</ns2:sub>
<ns3:sub>3</ns3:sub>
</root>

is there a way to select all nodes that contain the word "sub". (Due
to namespace constraints, I will be getting the subnodes as <ns1:sub>,
<ns2:sub> and so on.)

regards,
Amit.

You can use the XPath function 'contains' to search for 'sub' within the
element names.

For this XML:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="sub.xsl"?>
<root>
<ns1:sub>1</ns1:sub>
<ns2:sub>2</ns2:sub>
<ns3:sub>3</ns3:sub>
<ns1:nomatch>1</ns1:nomatch>
<ns2:nomatch>2</ns2:nomatch>
<ns3:nomatch>3</ns3:nomatch>
</root>

The following XSL transformation selects those 'sub' elements:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/root">
<html><head/>
<body>
<xsl:for-each select="*">
<xsl:if test="contains(name(.),'sub')">
<h2><xsl:value-of select="name(.)"/></h2>
</xsl:if>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Hopefully that is what you were looking for. Have fun!
-Scott
 
P

Patrick TJ McPhee

%
% <root>
% <ns1:sub>1</ns1:sub>
% <ns2:sub>2</ns2:sub>
% <ns3:sub>3</ns3:sub>
% </root>
%
% is there a way to select all nodes that contain the word "sub". (Due
% to namespace constraints, I will be getting the subnodes as <ns1:sub>,
% <ns2:sub> and so on.)

Assuming you use xpath to do the selection, the function local-name()
returns the name of the element sans name-space prefix. In XSLT, you
could have

<xsl:template match='local-name(.) = "sub"'>
...
</xsl>

Question: if this is really what you want, why do you have name-spaces
there at all?
 
R

Robin Johnson

<xsl:template match='local-name(.) = "sub"'>

Surely you mean said:
Question: if this is really what you want, why do you have name-spaces
there at all?

Maybe ns1:sub and ns2:sub are to be treated differently at some other point.
 

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,997
Messages
2,570,240
Members
46,830
Latest member
HeleneMull

Latest Threads

Top