Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 755
  • Last Modified:

Remove attribute form XML in java

How can I remove an attribute from XML? Below code is not working.

	private static Document removeXMLNSAttribute(Document doc) throws ParserConfigurationException, SAXException, IOException {
	    NodeList nodeList = doc.getElementsByTagName("*");
	    for ( int i = 0; i < nodeList.getLength(); i++ ) {
	    	Element ele = (Element) nodeList.item(i);
	    	if (ele.hasAttribute("xmlns")) {
	    		ele.removeAttribute("xmlns");
	    	}
	    }
	    return doc;
	}

Open in new window


The return value of above function still contain 'xmlns' attribute.
0
Ravi Kalla
Asked:
Ravi Kalla
1 Solution
 
Robert SchuttSoftware EngineerCommented:
I'm not the biggest java/xml expert (by far) but since they seem to be on holiday here is some working code for you, but to be honest I doubt it's the best way:
	private static Document removeXMLNSAttribute(Document doc) throws ParserConfigurationException, SAXException, IOException {
		NodeList nodeList = doc.getElementsByTagName("*");
		for ( int i = 0; i < nodeList.getLength(); i++ ) {
			if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
				Element ele = (Element) nodeList.item(i);
				NamedNodeMap nnm = ele.getAttributes();
				for (int a = nnm.getLength() - 1; a >= 0; a--) { // back to front because of remove in loop!
					Attr attr = (Attr)nnm.item(a);
					if (attr.getNodeName().startsWith("xmlns:")) {
						ele.removeAttributeNode(attr);
					}
				}
			}
		}
		return doc;
	}

Open in new window

For more information see for example http://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/Node.html#getAttributes__
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now