Today we’ll talk about parsing and generating XML documents based on the DOM
XNL documentation for general Web development:
Processing XML documents based on the DOM
1. DOM parsing XML documents
<? xml version="1.0" encoding="UTF-8"? > <accounts> <! -- define the age attribute --> < Account age="20" bankNo="10001"> <id>610500199909022342</id> <name> <money>5000.0</money> </account> <account age="21" bankNo="10002"> <id>610500199709022342</id> <name> <money>4500.0</money> </accounts>Copy the code
Entity class:
package com.yueqian.xml; /** * the entity class that encapsulates XML * @author LinChi
*
*/
public class Account {
private String bankNo;
private int age;
private String id;
private String name;
private double money;
public Account() {
super();
}
public Account(String bankNo, int age, String id, String name, double money) {
super();
this.bankNo = bankNo;
this.age = age;
this.id = id;
this.name = name;
this.money = money;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public String getBankNo() {
return bankNo;
}
public void setBankNo(String bankNo) {
this.bankNo = bankNo;
}
@Override
public String toString() {
return this.bankNo+"|"+this.age+"|"+this.id+"|"+this.name+"|"+this.money; }}Copy the code
Resolution:
/** * parses XML documents * @param filePath * @return
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public static List<Account> readXml (String filePath) throws a ParserConfigurationException, SAXException, IOException {/ / filter illegalif(filePath == null || filePath.length()<=0) {
System.out.println("ERROR: filePath args is null!"); // Returns the null listreturnCollections.EMPTY_LIST; } // create File File xmlFile = new File(filePath); // Check whether the file existsif(! xmlFile.exists()) { System.out.println("ERROR: filePath not exists!"); // Returns the null listreturnCollections.EMPTY_LIST; List<Account> xmlList = new ArrayList<Account>(); / / for DOM builder factory object DocumentBuilderFactory bf = DocumentBuilderFactory. NewInstance (); // Create the DOM builder DocumentBuilder build = bf.newDocumentBuilder(); Document doc = build.parse(xmlFile); // Get the root Element rootEle = doc.getDocumentElement(); // system.out.println (rootele.gettagName ()); NodeList accNodeList = rootele.getChildNodes (); // Iterate over each account labelfor(int i = 0; i<accNodeList.getLength(); Node Node = accnodelist.item (I); // System.out.println(node.getNodename ()); // Skip nodes with useless text information, i.e., nodes that are not Elementsif(! (node instanceof Element) ) {continue; } // Convert Node to Element Element accEle = (Element) Node; // Create a new Account object Account acc = new Account(); String ageAttr = null; String bankNo = null; NamedNodeMap accAttrs = Accele.getAttributes (); // Loop over all attribute valuesfor(int j = 0; j<accAttrs.getLength(); J++) {// loop over all attributes under the specified position Node attrNode = accattrs.item (j); Attr Attr = (Attr)attrNode; // Determine the attribute informationif("age".equals(attr.getNodeName())) {
ageAttr = attr.getNodeValue();
}
if("bankNo".equals(attr.getNodeName())) { bankNo = attr.getNodeValue(); } } System.out.println(); int age = 0; Try {age = integer.parseint (ageAttr.trim()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Set the age attribute acc.setage (age); // Set the bank account property acc.setBankno (bankNo); // Get the attribute label of the sublabel Account tagfor(int k = 0; k<accEle.getChildNodes().getLength(); k++) { Node subNode = accEle.getChildNodes().item(k);if(! (subNode instanceof Element) ) {continue; Element accField = (Element)subNode; // Check whether it is the name tagif("name".equals(accField.getNodename ())) {// Set the name attribute tag between elements using the Element object. } // Check whether it is an ID tagif("id".equals(accField.getNodename ())) {// Set the name attribute tag between elements using the Element object. } // Check whether it is a name tagif("money".equals(accField.getNodeName())) { double money = 0; try { money = Double.parseDouble(accField.getTextContent()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Set the name attribute tag between elements using the Element object. GetTextContent () acc.setMoney(money); }} // Add objects to the list xmllist.add (acc); }return xmlList;
}
Copy the code
Testing:
public static void main(String[] args) {
try {
List<Account> list = readXml("xml/Test.xml"); System.out.println(list); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Copy the code
Screenshot of results:
2. Generate XML documents in DOM mode
Generation:
/** * generate XML document * @param path file path * @param fileName fileName * @param data collection list * @return* @throws ParserConfigurationException * @throws TransformerException */ public static boolean writeXml(String Path, the String fileName, List < Account > data) throws a ParserConfigurationException, TransformerException {/ / illegal operationif(path == null || path.length()<=0 ||
fileName == null || fileName.length()<=0 ||
data == null || data.size()<=0) {
System.out.println("ERROR: filePath args is null!"); // Returns the null listreturn false; } File dir = new File(path); // Check whether the file exists and create it if it does notif(! dir.exists()) { dir.mkdirs(); } // Check whether a File exists xmlFile = new File(dir, fileName); / / get a DOM factory object DocumentBuilderFactory bf = DocumentBuilderFactory. NewInstance (); // Create builder DocumentBuilder build = bf.newDocumentBuilder(); // Create a DOM Document tree according to the builder Document doc = build.newDocument(); RootEle = doc.createElement("accounts"); AppendChild (rootEle); // Add the root node to the tree. // Loop through the list of Account objects to construct an XML representation of Accountfor(Account acc:data) {// Create Account Element accEle = doc.createElement("account"); // Set the attribute accele.setAttribute ("age", String.valueOf(acc.getAge()));
accEle.setAttribute("bankNo", acc.getBankNo());
//添加account节点到accounts上
rootEle.appendChild(accEle);
//添加id子标签
Element idEle = createSubElement(doc,"id",acc.getId()); AppendChild (idEle); // Add the id node to the account node accele.appendChild (idEle); Element nameEle = createSubElement(doc,"name",acc.getName()); AppendChild (nameEle); // Add the id node to the account node accele.appendChild (nameEle); MoneyEle = createSubElement(doc,"money",String.valueOf(acc.getMoney())); Accele.appendchild (moneyEle); // Add the id node to the account node accele.appendChild (moneyEle); } / / will add the tree structure of written to doc TransformerFactory factory = TransformerFactory. NewInstance (); Transformer tf = factory.newTransformer(); DOMSourcesource = new DOMSource(doc);
StreamResult result = new StreamResult(xmlFile);
tf.transform(source, result);
return true; } /** * Create an Element object with simple text content * @param doc * @param tagName * @param textContext * @return*/ private static Element createSubElement(Document doc,String tagName,String textContext) {// Create Element Element element = doc.createElement(tagName); // Add Text to the TextNode node. Text Text = doc.createTextNode(textContext); // Add text content to the tag element.appendChild(text);return element;
}
Copy the code
Testing:
Public static void main(String[] args) {List<Account> accList = new ArrayList<Account>(); accList.add(new Account("acc1003", 25, "610105200210102233" ,"Wang", 6000.0));
try {
System.out.println(writeXml("I:/"."accs.xml",accList)); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Copy the code
Screenshot of results:
true
DOM reads and writes XML.
package com.yueqian.xml; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; 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.Attr; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; import org.xml.sax.XMLFilter; /** * @author LinChi
*
*/
public class TestXml {
public static void main(String[] args) {
try {
List<Account> list = readXml("xml/Test.xml"); System.out.println(list); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); List<Account> accList = new ArrayList<Account>(); accList.add(new Account("acc1003", 25, "610105200210102233" ,"Wang", 6000.0));
try {
System.out.println(writeXml("I:/"."accs.xml",accList)); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); }} /** * Parses XML documents * @param filePath * @return
* @throws ParserConfigurationException
* @throws SAXException
* @throws IOException
*/
public static List<Account> readXml (String filePath) throws a ParserConfigurationException, SAXException, IOException {/ / filter illegalif(filePath == null || filePath.length()<=0) {
System.out.println("ERROR: filePath args is null!"); // Returns the null listreturnCollections.EMPTY_LIST; } // create File File xmlFile = new File(filePath); // Check whether the file existsif(! xmlFile.exists()) { System.out.println("ERROR: filePath not exists!"); // Returns the null listreturnCollections.EMPTY_LIST; List<Account> xmlList = new ArrayList<Account>(); / / for DOM builder factory object DocumentBuilderFactory bf = DocumentBuilderFactory. NewInstance (); // Create the DOM builder DocumentBuilder build = bf.newDocumentBuilder(); Document doc = build.parse(xmlFile); // Get the root Element rootEle = doc.getDocumentElement(); // system.out.println (rootele.gettagName ()); NodeList accNodeList = rootele.getChildNodes (); // Iterate over each account labelfor(int i = 0; i<accNodeList.getLength(); Node Node = accnodelist.item (I); // System.out.println(node.getNodename ()); // Skip nodes with useless text information, i.e., nodes that are not Elementsif(! (node instanceof Element) ) {continue; } // Convert Node to Element Element accEle = (Element) Node; // Create a new Account object Account acc = new Account(); String ageAttr = null; String bankNo = null; NamedNodeMap accAttrs = Accele.getAttributes (); // Loop over all attribute valuesfor(int j = 0; j<accAttrs.getLength(); J++) {// loop over all attributes under the specified position Node attrNode = accattrs.item (j); Attr Attr = (Attr)attrNode; // Determine the attribute informationif("age".equals(attr.getNodeName())) {
ageAttr = attr.getNodeValue();
}
if("bankNo".equals(attr.getNodeName())) { bankNo = attr.getNodeValue(); } } System.out.println(); int age = 0; Try {age = integer.parseint (ageAttr.trim()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Set the age attribute acc.setage (age); // Set the bank account property acc.setBankno (bankNo); // Get the attribute label of the sublabel Account tagfor(int k = 0; k<accEle.getChildNodes().getLength(); k++) { Node subNode = accEle.getChildNodes().item(k);if(! (subNode instanceof Element) ) {continue; Element accField = (Element)subNode; // Check whether it is the name tagif("name".equals(accField.getNodename ())) {// Set the name attribute tag between elements using the Element object. } // Check whether it is an ID tagif("id".equals(accField.getNodename ())) {// Set the name attribute tag between elements using the Element object. } // Check whether it is a name tagif("money".equals(accField.getNodeName())) { double money = 0; try { money = Double.parseDouble(accField.getTextContent()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (DOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Set the name attribute tag between elements using the Element object. GetTextContent () acc.setMoney(money); }} // Add objects to the list xmllist.add (acc); }returnxmlList; } /** * generate XML document * @param path file path * @param fileName fileName * @param data collection list * @return* @throws ParserConfigurationException * @throws TransformerException */ public static boolean writeXml(String Path, the String fileName, List < Account > data) throws a ParserConfigurationException, TransformerException {/ / illegal operationif(path == null || path.length()<=0 ||
fileName == null || fileName.length()<=0 ||
data == null || data.size()<=0) {
System.out.println("ERROR: filePath args is null!"); // Returns the null listreturn false; } File dir = new File(path); // Check whether the file exists and create it if it does notif(! dir.exists()) { dir.mkdirs(); } // Check whether a File exists xmlFile = new File(dir, fileName); / / get a DOM factory object DocumentBuilderFactory bf = DocumentBuilderFactory. NewInstance (); // Create builder DocumentBuilder build = bf.newDocumentBuilder(); // Create a DOM Document tree according to the builder Document doc = build.newDocument(); RootEle = doc.createElement("accounts"); AppendChild (rootEle); // Add the root node to the tree. // Loop through the list of Account objects to construct an XML representation of Accountfor(Account acc:data) {// Create Account Element accEle = doc.createElement("account"); // Set the attribute accele.setAttribute ("age", String.valueOf(acc.getAge()));
accEle.setAttribute("bankNo", acc.getBankNo());
//添加account节点到accounts上
rootEle.appendChild(accEle);
//添加id子标签
Element idEle = createSubElement(doc,"id",acc.getId()); AppendChild (idEle); // Add the id node to the account node accele.appendChild (idEle); Element nameEle = createSubElement(doc,"name",acc.getName()); AppendChild (nameEle); // Add the id node to the account node accele.appendChild (nameEle); MoneyEle = createSubElement(doc,"money",String.valueOf(acc.getMoney())); Accele.appendchild (moneyEle); // Add the id node to the account node accele.appendChild (moneyEle); } / / will add the tree structure of written to doc TransformerFactory factory = TransformerFactory. NewInstance (); Transformer tf = factory.newTransformer(); DOMSourcesource = new DOMSource(doc);
StreamResult result = new StreamResult(xmlFile);
tf.transform(source, result);
return true; } /** * Create an Element object with simple text content * @param doc * @param tagName * @param textContext * @return*/ private static Element createSubElement(Document doc,String tagName,String textContext) {// Create Element Element element = doc.createElement(tagName); // Add Text to the TextNode node. Text Text = doc.createTextNode(textContext); // Add text content to the tag element.appendChild(text);returnelement; }}Copy the code
That’s all for today! Expect tomorrow’s SAX parsing of XML documents