开发者

extracting portion of xml by specifying without namespace prefix in xslt

one with namespace prefix with 'emp'

<?xml version="1.0" encoding="UTF-8"?>
<emp:Employees xmlns:emp="http://www.xyz.com">
    <emp:EmployeeDetails>
        <emp:EmployeeCompanyDetails>
            <emp:CompanyName>XYZ</emp:CompanyName>
            <emp:Desgination>Engineer</emp:Desgination>
            <emp:YearOfExp>8</emp:YearOfExp>
            <emp:开发者_JAVA百科Department>HR</emp:Department>
            <emp:ProjectDetails>
                <emp:ProjectName>ABC</emp:ProjectName>
                <emp:Client>ZZZ</emp:Client>
                <emp:Manager>MMMM</emp:Manager>
            </emp:ProjectDetails>
        </emp:EmployeeCompanyDetails>
    </emp:EmployeeDetails>
</emp:Employees>

and the other without namespace prefix.

<emp:Employees xmlns:emp="http://www.xyz.com">
    <EmployeeDetails>
        <EmployeeCompanyDetails>
            <CompanyName>XYZ</CompanyName>
            <Desgination>Engineer</Desgination>
            <YearOfExp>8</YearOfExp>
            <Department>HR</Department>
            <ProjectDetails>
                <ProjectName>ABC</ProjectName>
                <Client>ZZZ</Client>
                <Manager>MMMM</Manager>
            </ProjectDetails>
        </EmployeeCompanyDetails>
    </EmployeeDetails>
</emp:Employees>

I have written xslt below to extract only <ProjectDetails> that has no namespace prefix defined.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:emp="http://www.xyz.com" version="1.0">
    <xsl:template match="/">
        <emp:ProjectDetails>        
            <xsl:copy-of select="*//ProjectDetails/*" /> 
            <xsl:copy>
                <!--xsl:apply-templates /-->
            </xsl:copy>
        </emp:ProjectDetails>
    </xsl:template>
    <xsl:template match="*">
        <xsl:element name="ns:{local-name()}">
            <xsl:apply-templates select="@*|node()" />
        </xsl:element>
    </xsl:template>
    <xsl:template match="@*">
        <xsl:attribute name="{local-name()}">
            <xsl:value-of select="." />
        </xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

Above xslt will work if input xml comes without namespace prefix. Suppose input xml comes with namespace prefix emp:, then i need to change my xslt code to <xsl:copy-of select="*//emp:ProjectDetails/*" /> .

My question : Is there anyway we can write a common xslt to extract portion of xml.


You can use:

<xsl:copy-of select="//*[local-name() = 'ProjectDetails']"/>


Well with XSLT 2.0 you can use a wildcard select="*//*:ProjectDetails/*". And with XSLT 1.0 nothing prevents you from using select="*//emp:ProjectDetails/* | *//ProjectDetails/*" or select="*//*[local-name() = 'ProjectDetails']/*". That approach allows you to handle both kind of input documents with one select attribute in your stylesheet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜