The main research in this article is the relevant code of Java using DOM to add, delete, modify and search XML documents. The specific examples are as shown below.
source code:
package com.zc.homeWork18;import java.io.File;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import javax.xml.xpath.XPath;import javax.xml.xpath.XPathConstants;import javax.xml.xpath.XPathExpressionException;import javax.xml.xpath.XPathFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class XMLWriter { private static String xmlPath = "src//com//zc//homeWork18//MyXml.xml"; public static void getFamilyMemebers() { /* * Create a file factory instance*/ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // If the created parser must delete spaces in the element content when parsing an XML document, it is true, otherwise it is false dbf.setIgnoringElementContentWhitespace(true); try { /* * Create a file object*/ DocumentBuilder db = dbf.newDocumentBuilder();// Create a parser to parse XML document Document doc = db.parse(xmlPath); // Use dom to parse an XML file/* * Go through the list and extract the XML file data*/ // Get all related nodes according to the node name NodeList sonlist = doc.getElementsByTagName("son"); for (int i = 0; i < sonlist.getLength(); i++) // Looping processing object { // processing of node attributes Element son = (Element) sonlist.item(i); // All child nodes in the loop node son for (Node node = son.getFirstChild(); node != null; node = node .getNextSibling()) { // Determine whether it is an element node if (node.getNodeType() == Node.ELEMENT_NODE) { String name = node.getNodeName(); String value = node.getFirstChild().getNodeValue(); System.out.println(name + " : " + value); } } } } catch (Exception e) { System.out.println(e.getMessage()); } } } // Modify public static void modifySon() { // Create file factory instance DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(true); try { // Get DOM document instance from XML document DocumentBuilder db = dbf.newDocumentBuilder(); // Get Document object Document xmldoc = db.parse(xmlPath); // Get root node Element root = xmldoc.getDocumentElement(); // Position node with id 001 Element per = (Element) selectSingleNode("/father/son[@id='001']", root); // Change the content of the age node to 28 per.getElementsByTagName("age").item(0).setTextContent("28"); // Save TransformerFactory factory = TransformerFactory.newInstance(); Transformer former = factory.newTransformer(); former.transform(new DOMSource(xmldoc), new StreamResult(new File(xmlPath))); } catch (Exception e) { System.out.println(e.getMessage()); } } // Get the target node, delete, and finally save public static void discardSon() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(true); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document xmldoc = db.parse(xmlPath); // Get the root node Element root = xmldoc.getDocumentElement(); // Position the node with id=002 in the root node Element son = (Element) selectSingleNode("/father/son[@id='002']", root); // Delete the node root.removeChild(son); // Save TransformerFactory factory = TransformerFactory.newInstance(); Transformer former = factory.newTransformer(); former.transform(new DOMSource(xmldoc), new StreamResult(new File(xmlPath))); } catch (Exception e) { System.out.println(e.getMessage()); } } // Add a new node public static void createSon() { // Create file factory instance DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringElementContentWhitespace(false); try { DocumentBuilder db = dbf.newDocumentBuilder(); // Create Document object Document xmldoc = db.parse(xmlPath); // Get the root node Element root = xmldoc.getDocumentElement(); // Create node son, set the corresponding id to 004 Element son = xmldoc.createElement("son"); son.setAttribute("id", "004"); // Create node name Element name = xmldoc.createElement("name"); name.setTextContent("Little Son"); son.appendChild(name); // Create node age Element age = xmldoc.createElement("age"); age.setTextContent("0"); son.appendChild(age); // Add son to the root node root.appendChild(son); // Save TransformerFactory factory = TransformerFactory.newInstance(); Transformer former = factory.newTransformer(); former.transform(new DOMSource(xmldoc), new StreamResult(new File(xmlPath))); } catch (Exception e) { System.out.println(e.getMessage()); } } // Modify node information public static Node selectSingleNode(String expression, Element source) { Node result = null; // Create XPath factory XPathFactory xpathFactory = XPathFactory.newInstance(); //Create XPath object XPath xpath = xpathFactory.newXPath(); try { result = (Node) xpath.evaluate(express, source, XPathConstants.NODE); System.out.println(result); } catch (XPathExpressionException e) { System.out.println(e.getMessage()); } return result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~~~~~~~~~~~~~~~~~~~~ System.out.println("Add data"); getFamilyMemebers(); }}XML files
<?xml version="1.0" encoding="UTF-8" standalone="no"?><father> <son id="001"> <name>Boss</name> <age>20</age> </son> <son id="002"> <name>Second</name> <age>18</age> </son> <son id="003"> <name>Ladder</name> <age>13</age> </son></father>
Summarize
The above is the entire content of this article about the example code of Java using DOM to add, delete, modify and search XML documents. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!