Home > Mobile >  XLST - select only elements with a specific attribute value (but get all)
XLST - select only elements with a specific attribute value (but get all)

Time:07-14

When I select elements with a specific attribute value, still all elements are selected. Why? So, I applied a standard solution but it does not work. Tried many alternatieves without success. Yup, XLST is pretty new for me.

XLST:

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:template match="/company/staff[@attrib = 'select']">
        <parent>
            <header>Some inserted text</header>
            <xsl:copy-of select="staff"/>
        </parent>
    </xsl:template>
</xsl:stylesheet>

Example XML file:

<?xml version="1.0" encoding="utf-8"?>
<company>
    <staff attrib="select" id="1001">
        <name>should-1</name>
        <role>copy-1</role>
    </staff>
    <staff id="1002">
        <name>should-3</name>
        <role>not-copy-3</role>
    </staff>
    <staff attrib="select" id="1003">
        <name>should-2</name>
        <role>copy-2</role>
    </staff>
</company>

In the result I see 'staff' element with id="1002" even when it does not have the specific attribute value.

Wanted result:

<?xml version="1.0" encoding="UTF-8"?><parent><header>Some inserted text</header><company>
    <staff attrib="select" id="1001">
        <name>should-1</name>
        <role>copy-1</role>
    </staff>
    <staff attrib="select" id="1003">
        <name>should-2</name>
        <role>copy-2</role>
    </staff>
</company></parent>

Actual result:

<?xml version="1.0" encoding="UTF-8"?><parent><header>Some inserted text</header><company>
    <staff attrib="select" id="1001">
        <name>should-1</name>
        <role>copy-1</role>
    </staff>
    <staff id="1002">
        <name>should-3</name>
        <role>not-copy-3</role>
    </staff>
    <staff attrib="select" id="1003">
        <name>should-2</name>
        <role>copy-2</role>
    </staff>
</company></parent>

CodePudding user response:

You can do simply:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/company">
    <parent>
        <header>Some inserted text</header>
        <xsl:copy-of select="staff[@attrib = 'select']"/>
    </parent>
</xsl:template>

</xsl:stylesheet>
  • Related