XPath: Delete all attributes of a node except some special ones

Today I needed to delete all attributes of a XML Node except of some special ones. I found a solution by using the local-name() method. An expression like local-name()!=’attributeKey’ excludes the attribute with the name “attributeKey” from the selection. In a XML Node like:

<ent:address street="MuellerWeg" streetnumber="151" city="Cologne" country="Germany" zipcode="50935" xsi:type="ent:StreetnumberAddress">
</ent:address>

A XPath expression like:

/ent:address /@*[local-name()!='street' and local-name()!='type' and local-name()!='zipcode']

will delete all attributes exept “street” and “zipcode”. If you don’t want to delete the “xsi:type” attribute you have to add “and local-name()!=’type'”.

Unfortunately I did not found a method to find the attribute name and the namespace (eg. xsi:type). This would minimize the risk to filter the wrong attribute.

A easy way to check XPath expressions is to use the “XPath Checker” plugin for Firefox. You can find it here >>

Leave a Reply

Your email address will not be published. Required fields are marked *