Remove Empty Attributes from XML

Posted by er4z0r on Stack Overflow See other posts from Stack Overflow or by er4z0r
Published on 2010-03-19T11:15:04Z Indexed on 2010/03/19 11:51 UTC
Read the original article Hit count: 271

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about Xml