java uses DOM to add delete change and look up XML documents
- 2021-01-19 22:14:51
- OfStack
This paper mainly studies java using DOM to add, delete, modify and check XML documents related codes, specific examples are shown as follows.
The 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 you create a parser that is parsing XML The whitespace in the element content must be removed when the document is written true , or for false
dbf.setIgnoringElementContentWhitespace(true);
try {
/*
* Creating a file object
*/
DocumentBuilder db = dbf.newDocumentBuilder();// Create a parser and parse XML The document
Document doc = db.parse(xmlPath); // use dom parsing xml file
/*
* Go through the list XML Data extraction of files
*/
// Retrieves all related nodes by node name
NodeList sonlist = doc.getElementsByTagName("son");
for (int i = 0; i < sonlist.getLength(); i++) // Loop processing object
{
// Processing of node attributes
Element son = (Element) sonlist.item(i);
// Loop nodes son All child nodes in
for (Node node = son.getFirstChild(); node != null; node = node
.getNextSibling()) {
// Determine if 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 the
public static void modifySon() {
// Create a file factory instance
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace(true);
try {
// from XML Fetch in document DOM Document instance
DocumentBuilder db = dbf.newDocumentBuilder();
// To obtain Document object
Document xmldoc = db.parse(xmlPath);
// Get the root node
Element root = xmldoc.getDocumentElement();
// positioning id for 001 The nodes of the
Element per = (Element) selectSingleNode("/father/son[@id='001']",
root);
// will age Change the content of the 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 it, and finally save it
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();
// Locates in the root node id=002 The nodes of the
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());
}
}
// The new node
public static void createSon() {
// Create a 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 a node son , set the corresponding id for 004
Element son = xmldoc.createElement("son");
son.setAttribute("id", "004");
// Create a node name
Element name = xmldoc.createElement("name");
name.setTextContent(" The younger son ");
son.appendChild(name);
// Create a node age
Element age = xmldoc.createElement("age");
age.setTextContent("0");
son.appendChild(age);
// the son Add 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 express, Element source) {
Node result = null;
// create XPath The 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;
}
// print
public static void main(String[] args) {
getFamilyMemebers();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
modifySon();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Modify the data ");
getFamilyMemebers();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
discardSon();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Delete the data ");
getFamilyMemebers();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
createSon();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Add data ");
getFamilyMemebers();
}
}
XML file
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<father>
<son id="001">
<name> The eldest brother </name>
<age>20</age>
</son>
<son id="002">
<name> The old 2</name>
<age>18</age>
</son>
<son id="003">
<name> The old 3</name>
<age>13</age>
</son>
</father>
conclusion
The above is this article about java using DOM to add, delete, modify and check XML documents all the content of the operation example code, I hope to help you. Interested friends can continue to refer to the site of other related topics, if there are shortcomings, welcome to leave a message to point out. Thank you for your support!