Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7986935
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T11:59:50+00:00 2026-06-04T11:59:50+00:00

I am trying to use Java to remove all xml attributes from a XML

  • 0

I am trying to use Java to remove all xml attributes from a XML file that match a attribute-name. I am stuck at this point. At the bottom of this code I am able to get the attribute value of each node as I loop through but I can’t figure out how to delete the attribute from the Node altogether . Any ideas?

import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.*;
import org.xml.sax.SAXException;


public class StripAttribute { 

  public static void main(String[] args) { 

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
    factory.setNamespaceAware(true); 
    org.w3c.dom.Document doc = null;
    NodeList nodes = null;
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
      DocumentBuilder db = dbf.newDocumentBuilder(); 
      doc = db.parse("a.xml");
      nodes = doc.getChildNodes();
    }  catch (IOException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    }
    for ( int i = 0; i < nodes.getLength(); i++ ) { 
      String id = nodes.item(i).getNodeValue();
      if ( id.equals("siteKey")) {
        Element el = ((Attr) nodes.item(i)).getOwnerElement(); 
        el.removeAttribute(id);
      }
    } 

    Transformer transformer;
    StreamResult result = null;
    try {
      transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      result = new StreamResult(new StringWriter()); 
      DOMSource source = new DOMSource(doc); 
      transformer.transform(source, result); 
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    } 
    String xmlString = result.getWriter().toString(); 
    System.out.println(xmlString); 
  } 
}    

Here is a sample of the XML I want to transform:

https://gist.github.com/2784907

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T11:59:52+00:00Added an answer on June 4, 2026 at 11:59 am

    Try:

    for ( int i = 0; i < nodes.getLength(); i++ ) { 
        String id = nodes.item(i).getNodeValue();
        if ( id.equals("siteKey")) {
            //doc.removeChild(nodes.item(i));
            Element el = ((Attr) nodes.item(i)).getOwnerElement(); 
            el.removeAttribute(id);
        }
    } 
    

    It seems that the nodes returned by the query are detached from the document so getParentNode is null. – no, they are not detached, I updated the code.

    I found an article that says that the nodes returned by XPathExpression are still attached to the document.

    You’re original code + the above change:

    public static void main(String[] args) throws Exception {
    
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document doc = null;
        NodeList nodes = null;
        Set<String> ids = null;
        try {
            doc = factory.newDocumentBuilder().parse(new File("d:/a.xml"));
    
            XPathExpression expr = XPathFactory.newInstance().newXPath().compile("//@siteKey");
            ids = new HashSet<String>();
            nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
    
        for (int i = 0; i < nodes.getLength(); i++) {
            String id = nodes.item(i).getNodeValue();
            if (id.equals("siteKey")) {
                Element el = ((Attr) nodes.item(i)).getOwnerElement();
                el.removeAttribute(id);
            }
        }
    
        int dupes = 0;
        for (int i = 0; i < nodes.getLength(); i++) {
            String id = nodes.item(i).getNodeValue();
            if (ids.contains(id)) {
                System.out.format("%s is duplicate\n\n", id);
                dupes++;
            } else {
                ids.add(id);
            }
        }
    
        System.out.format("Total ids = %d\n Total Duplicates = %d\n", ids.size(), dupes);
    
        Transformer transformer;
        StreamResult result = null;
        try {
            transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            result = new StreamResult(new StringWriter());
            DOMSource source = new DOMSource(doc);
            transformer.transform(source, result);
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerFactoryConfigurationError e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
    
        String xmlString = result.getWriter().toString();
        System.out.println(xmlString);
    
    } 
    

    Update:

    for (int i = 0; i < nodes.getLength(); i++) {
        String id = nodes.item(i).getNodeValue();
        Element el = ((Attr) nodes.item(i)).getOwnerElement();
        el.removeAttribute(id);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm really stuck trying to use java wrapper library for opencv's cvMatchTemplate. See this
I'm trying to find the best way to use Java libraries that were installed
I'm trying to use this formula in JAVA : (-ln(1-L))/L I'm not sure how
I'm trying to use the Saxon processor from java. I'm using the the saxon9ee.jar
I came from a java background, and I was trying to use protocol like
I'm trying to use the example taken from the http://java.sun.com/products/jfc/tsc/articles/treetable2/index.html , in which I've
I am trying to use Java's useDelimiter method on it's Scanner class to do
I am trying use a Java Uploader in a ROR app (for its ease
I'm trying to re-use a Java generic collection I wrote, looks a lot like
I'm trying to use checkstyle for a java project but I can't seem to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.