Java & Xml tutorial (3) use DOM to modify XML file content

Source: Internet
Author: User
The DOM parsing method can also be used to modify XML data. we can use it to add, delete, modify, and modify element attributes.

The DOM parsing method can also be used to modify XML data. we can use it to add, delete, modify, and modify element attributes.

The content of our XML file is as follows:
Employee. xml

 
     
          
   
    Pankaj
           29        
   
    Java Developer
           
   
    Male
       
      
          
   
    Lisa
           35        
   
    CSS Developer
           
   
    Female
       
  
 

We will modify the content of the XML file:
1. modify the "id" attribute value based on the gender of the employee. append "M" to the id attribute value of Male to Female) append "F" to the id property value ".
2. modify the value of the name element to uppercase.
3. the "gender" element has no meaning. let's delete it.
4. add a "salary" node under the employee node.
After completing the preceding operations, save the content in a new xml file.
The following is the Java program code parsed using DOM:
ModifyXMLDOM. java

Package com. journaldev. xml; import java. io. file; import java. io. IOException; 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. transformerException; import javax. xml. transform. transformerFactory; import javax. xml. transform. dom. DOMSource; import javax. xml. transform. stream. streamResult; import org. w3c. dom. document; import org. w3c. dom. element; import org. w3c. dom. node; import org. w3c. dom. nodeList; import org. xml. sax. SAXException; public class ModifyXMLDOM {public static void main (String [] args) {String filePath = "employee. xml "; File xmlFile = new File (filePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory. newInstance (); DocumentBuilder dBuilder; try {dBuilder = dbFactory. newDocumentBuilder (); Document doc = dBuilder. parse (xmlFile); doc. getDocumentElement (). normalize (); // update attribute value updateAttributeValue (doc); // update Element value updateElementValue (doc); // delete element deleteElement (doc ); // add new element addElement (doc); // write the updated document to file or console doc. getDocumentElement (). normalize (); TransformerFactory transformerFactory = TransformerFactory. newInstance (); Transformer transformer = transformerFactory. newTransformer (); DOMSource source = new DOMSource (doc); StreamResult result = new StreamResult (new File ("employee_updated.xml"); transformer. setOutputProperty (OutputKeys. INDENT, "yes"); transformer. transform (source, result); System. out. println ("XML file updated successfully");} catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {e1.printStackTrace () ;}} private static void addElement (Document doc) {NodeList employees = doc. getElementsByTagName ("Employee"); Element emp = null; // loop for each employee for (int I = 0; I
 
  

Output xml file content:
Employee_updated.xml

   
       
            
     
      PANKAJ
             29        
     
      Java Developer
         
     
      10000
     
        
            
     
      LISA
             35        
     
      CSS Developer
         
     
      10000
     
    
   

Original article address :#

The DOM parsing method can also be used to modify XML data. we can use it to add, delete, modify, and modify element attributes.
The content of our XML file is as follows:
Employee. xml

   
       
            
     
      Pankaj
             29        
     
      Java Developer
             
     
      Male
         
        
            
     
      Lisa
             35        
     
      CSS Developer
             
     
      Female
         
    
   

We will modify the content of the XML file:
1. modify the "id" attribute value based on the gender of the employee. append "M" to the id attribute value of Male to Female) append "F" to the id property value ".
2. modify the value of the name element to uppercase.
3. the "gender" element has no meaning. let's delete it.
4. add a "salary" node under the employee node.
After completing the preceding operations, save the content in a new xml file.
The following is the Java program code parsed using DOM:
ModifyXMLDOM. java

Package com. journaldev. xml; import java. io. file; import java. io. IOException; 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. transformerException; import javax. xml. transform. transformerFactory; import javax. xml. transform. dom. DOMSource; import javax. xml. transform. stream. streamResult; import org. w3c. dom. document; import org. w3c. dom. element; import org. w3c. dom. node; import org. w3c. dom. nodeList; import org. xml. sax. SAXException; public class ModifyXMLDOM {public static void main (String [] args) {String filePath = "employee. xml "; File xmlFile = new File (filePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory. newInstance (); DocumentBuilder dBuilder; try {dBuilder = dbFactory. newDocumentBuilder (); Document doc = dBuilder. parse (xmlFile); doc. getDocumentElement (). normalize (); // update attribute value updateAttributeValue (doc); // update Element value updateElementValue (doc); // delete element deleteElement (doc ); // add new element addElement (doc); // write the updated document to file or console doc. getDocumentElement (). normalize (); TransformerFactory transformerFactory = TransformerFactory. newInstance (); Transformer transformer = transformerFactory. newTransformer (); DOMSource source = new DOMSource (doc); StreamResult result = new StreamResult (new File ("employee_updated.xml"); transformer. setOutputProperty (OutputKeys. INDENT, "yes"); transformer. transform (source, result); System. out. println ("XML file updated successfully");} catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {e1.printStackTrace () ;}} private static void addElement (Document doc) {NodeList employees = doc. getElementsByTagName ("Employee"); Element emp = null; // loop for each employee for (int I = 0; I
   
    

Output xml file content:
Employee_updated.xml

     
         
              
       
        PANKAJ
               29        
       
        Java Developer
           
       
        10000
       
          
              
       
        LISA
               35        
       
        CSS Developer
           
       
        10000
       
      
     

The above is the Java & Xml tutorial (3). use DOM to modify the content of the XML file. For more information, see PHP Chinese website (www.php1.cn )!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.