Reputation: 1032
I have this xml from a service:
<GetClass_RS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Class xmlns="http://www.company.com/erp/worker/soa/2013/03">
<student>Jack</student>
<student>Harry</student>
<student>Rebecca</student>
<teacher>Mr. Bean</teacher>
</Class>
</GetClass_RS>
I want to match Class/student like this:
<xsl:template match="Class/student">
<p>
<xsl:value-of select="."/>
</p>
</xsl:template>
The problem is due to the class's namespace the match doesn't work:
<Class xmlns="http://www.company.com/erp/worker/soa/2013/03">
I would like to ignore the namespace in the match.
Upvotes: 1
Views: 3571
Reputation: 22617
Good point, I suppose I don't need to ignore it. I just need to match the element with the namespace
First of all, note that if a namespace is declared like this:
<Class xmlns="http://www.company.com/erp/worker/soa/2013/03">
Then it applies to all its child elements, too. In other words, in your XML input, student
and teacher
elements are also in that namespace.
If elements in your input XML have a namespace, you have to mention that particular namespace in your XSLT stylesheet as well. The following line:
xmlns:class="http://www.company.com/erp/worker/soa/2013/03"
Declares this namespace and defines a prefix. Prefixing an element is like a shorthand way of declaring its namespace.
Stylesheet
I have added a template that matches teacher
elements. Otherwise, their text content is output via the default behaviour of your XSLT processor.
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:class="http://www.company.com/erp/worker/soa/2013/03">
<xsl:output method="xml" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="class:Class/class:student">
<p>
<xsl:value-of select="."/>
</p>
</xsl:template>
<xsl:template match="class:teacher"/>
</xsl:stylesheet>
Output
<?xml version="1.0" encoding="UTF-8"?>
<p xmlns:class="http://www.company.com/erp/worker/soa/2013/03">Jack</p>
<p xmlns:class="http://www.company.com/erp/worker/soa/2013/03">Harry</p>
<p xmlns:class="http://www.company.com/erp/worker/soa/2013/03">Rebecca</p>
As suggested by @michael.hor257k, if you add exclude-result-prefixes="class"
to the stylesheet
element, the elements are output without a namespace:
<?xml version="1.0" encoding="UTF-8"?>
<p>Jack</p>
<p>Harry</p>
<p>Rebecca</p>
Upvotes: 3