Remove Empty Attributes from XML
- by er4z0r
Hi,
I have a buggy xml that contains empty attributes and I have a parser that coughs on empty attributes.
I have no control over the generation of the xml nor over the parser that coughs on empty attrs. So what I want to do is a pre-processing step that simply removes all empty attributes.
I have managed to find the empty attribus, but now I don't know how to remove them:
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
XPathExpression expr = xpath.compile("//@*");
Object result = expr.evaluate(d, XPathConstants.NODESET);
if (result != null) {
NodeList nodes = (NodeList) result;
for(int node=0;node<nodes.getLength();node++)
{
Node n = nodes.item(node);
if(isEmpty(n.getTextContent()))
{
this.log.warn("Found empty attribute declaration "+n.toString());
NamedNodeMap parentAttrs = n.getParentNode().getAttributes();
parentAttrs.removeNamedItem(n.getNodeName());
}
}
}
This code gives me a NPE when accessing n.getParentNode().getAttributes().
But how can I remove the empty attribute from an element, when I cannot access the element?