AddyProg
AddyProg

Reputation: 3050

Removing XML node Using Xpath

I am trying to delete some nodes from XML document but its not working here is the XML

<?xml version="1.0" encoding="UTF-8" ?> 
 <reg>
 <user>
  <Name>adik</Name> 
  <Email>[email protected]</Email> 
  <Picture>/storage/sdcard0/XLEZData/EZImage/20130425163759.PNG</Picture> 
  <LastEdited>7 Apr 2014 09:28:27</LastEdited> 
  </user>
 <user>
  <Name>adil</Name> 
  <Email>[email protected]</Email> 
  <Picture>/storage/sdcard0/DCIM/Camera/20140318_165923(0).jpg</Picture> 
  <LastEdited>7 Apr 2014 09:29:06</LastEdited> 
  </user>
</reg>

and here is the code

   private void DeleteRecord(String sEmail) {
        try {

            ////
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            Document document = dbf.newDocumentBuilder().parse(new File(
                    Environment.getExternalStorageDirectory()
                    + "/Reginfo/output/data.xml"));

            XPathFactory xpf = XPathFactory.newInstance();
            XPath xpath = xpf.newXPath();
            XPathExpression expression = xpath.compile("//reg/user[Email = '" + sEmail + "']");
            Log.v("expression", expression.toString());
            Node b13Node = (Node) expression.evaluate(document, XPathConstants.NODE);
            b13Node.getParentNode().removeChild(b13Node);
             try{
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer t = tf.newTransformer();
            t.transform(new DOMSource(document), new StreamResult(System.out));
             }
             catch(Exception e){}
            ////
        }


         catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }

    }

what i want is to delete whole user node with its children Email Name, LastEdited and Picture

Upvotes: 0

Views: 230

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167436

Try xpath.compile("//reg/user[Email = '" + sEmail + "']");.

If the XML has namespaces then see http://www.edankert.com/defaultnamespaces.html#JAXP_XPathFactory on how to use the JAXP XPath API with namespaces to select nodes in a namespace.

Upvotes: 1

Related Questions