I have a number of XML files containing lots of overhead. I wish to keep only about 20 specific elements and filter out anything else. I know all the names of the elements I want to keep, I also know whether or not they are child elements and who are their parents. These elements that I want to keep after the transformation need to still have their original hierarchic placement.
E.g. I want to keep ONLY
<ns:currency>
in;
<ns:stuff>
<ns:things>
<ns:currency>somecurrency</ns:currency>
<ns:currency_code/>
<ns:currency_code2/>
<ns:currency_code3/>
<ns:currency_code4/>
</ns:things>
</ns:stuff>
And make it look like this;
<ns:stuff>
<ns:things>
<ns:currency>somecurrency</ns:currency>
</ns:things>
</ns:stuff>
What would be the best way of constructing an XSLT to accomplish this?
This general transformation:
when applied on the provided XML document (with namespace definition added to make it well-formed):
produces the wanted result (white-listed elements and their structural relations are preserved):
Explanation:
The identity rule/template copies all nodes "as-is".
The stylesheet contains a top-level
<ns:WhiteList>
element whose<name>
children specify all white-listed element's names -- the elements that are to be preserved with their structural relationships in the document.The
<ns:WhiteList>
element is best kept in a separate document so that the current stylesheet will not need to be edited with new names. Here the whitelist is in the same stylesheet just for convenience.One single template is overriding the identity template. It doesn't process (deletes) any element that is not white-listed and has no descendent that is white-listed.
In XSLT you usually don't remove the elements you want to drop, but you copy the elements you want to keep:
The example above copies only
currency
andcurrency_code3
. The output is as follows:Note: I added a namespace declaration for your prefix
ns
.If you want to copy everything except a few elements, you may see this answer