DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: How to remove an Element from XML by confirming Attribute of that element

  1. #1
    Join Date
    Nov 2007
    Posts
    1

    How to remove an Element from XML by confirming Attribute of that element

    Hi guys

    I have an XML file where i have all users DB. Now i want to remove a user from that XML file. I want to check an user id attribute which is uniqe with existing users in XML file, if its the same user then delete this user from XML file and save the changes in XML file.

    here is my XML file:
    Code:
    <?xml version="1.0" encoding="UTF-8"?>
    <users>
    <user id="zahid" password="X8UrUN79avT27LYwUESiliAV328=" name="Zahid Nawaz" phone="9599808" email="zahid.nawaz@gmx.de" role="Tnr+vPuuAAsix8heVWD4mioCgLQ=" />
    <user id="Admin" name="alpha beta" password="fEqNCco3Yq9h5ZUglD3CZJT4lBs=" phone="456782656" email="admin@myDomain.de" role="Tnr+vPuuAAsix8heVWD4mioCgLQ=" />
    <user id="Guest" name="beta alpha" password="+ml3yZuAnbaOHFaIjsOL0ARxmzk=" phone="8765432" email="guest@myDomain.de" role="+s6D7jAUvcj5ggPMlOLokiJFLpA=" /><user id="Guest1" name="unknown unknown" password="+ml3yZuAnbaOHFaIjsOL0ARxmzk=" phone="123122112" email="guest1@mydomain.de" role="+s6D7jAUvcj5ggPMlOLokiJFLpA=" />
    </users>
    for example i want to delete a user which have user id= Guest.

    How can i do it in Java. Any code example please.

    Till now i tried the following code which give null pointer exception at following line

    element.getParentNode().removeChild(element);

    Code:
    public String removeUserByID(String id) throws Exception{
    			
    		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    	        DocumentBuilder builder = factory.newDocumentBuilder();
    	        TransformerFactory tFactory = TransformerFactory.newInstance();
    	        Transformer tFormer = tFactory.newTransformer();
    		doc = builder.parse(usersXml);//XML File Path
    	        Element element = (Element)doc.getElementsByTagName("user id="+id).item(0);
    //	        Remove the node
    	        element.getParentNode().removeChild(element);
    //	        Normalize the DOM tree to combine all adjacent nodes
    	        doc.normalize();
    	        FileOutputStream fos = new FileOutputStream(this.usersXml);
    			XMLOutputter out = new XMLOutputter();
    			out.output(((org.jdom.Document)doc), fos);
    		/*	Source source = new DOMSource(doc);
    	        Result dest = new StreamResult(System.out);
    	        tFormer.transform(source, dest);
    	        System.out.println();
    	      */  
    	        return "true";
    	}
    if following line i m trying to use first attribute of my XML file where i am passing a string which is for example like "user id=Guest". id is a string which have user Id "Guest".
    Code:
    Element element = (Element)doc.getElementsByTagName("user id="+id).item(0);
    Waiting 4 reply

    Thanking u in Advance.

  2. #2
    Join Date
    Nov 2007
    Posts
    1
    Hi,

    Well after waiting a week where nobody has written back me. I started digging into XML, Jdom library. There i find very simple solution for deleting an element from XML file by confirming its attribute value.here i am posting my solution.
    Code:
    public boolean removeUserByID(String id){
           String fileName = "C:/users.xml";
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(fileName );
            Element root = doc.getRootElement();
            Iterator userListe = root.getChildren("user").iterator();
            while (userListe.hasNext()) {
                Element eUser = (Element) userListe.next();
                if(eUser.getAttribute("id").getValue().equals(id)){
                   
                    root.removeContent(eUser);
                    saveInFile(fileName, doc);
                    return true;
                }
            }
            return false;
        }
     
     
     public String saveList(String fileName, Document doc) {
    		try {
    			FileOutputStream fos = new FileOutputStream(fileName);
    			XMLOutputter out = new XMLOutputter();
    			out.output(doc, fos);
    			return "true";
     
    		} catch (Exception e) {
    			return "false";
    		}
    	}
    So its the whole code to delete and save back in xml file

    bye

  3. #3
    Join Date
    Apr 2007
    Location
    Sterling Heights, Michigan
    Posts
    8,663
    Thanks for posting your solution. It could help someone else with the same or similiar problem.

Similar Threads

  1. Replies: 1
    Last Post: 10-31-2005, 02:57 PM
  2. How long before the next version??
    By _CAG in forum .NET
    Replies: 146
    Last Post: 08-12-2002, 10:40 PM
  3. Re: App Object (fixes)
    By Rob Teixeira in forum .NET
    Replies: 129
    Last Post: 06-06-2002, 05:23 AM
  4. Getting the attribute value of an XML Element
    By Greg Rothlander in forum XML
    Replies: 2
    Last Post: 06-26-2001, 12:04 PM
  5. Data Junction Announces XML Junction 7.51
    By Tim Frost in forum xml.announcements
    Replies: 0
    Last Post: 04-02-2001, 10:53 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center