基于Java实现XML文件的解析与更新攻略
目录
- XML简介
- 使用Java自带API解析XML
- 使用第三方库解析XML
- 使用Java自带API更新XML
- 使用第三方库更新XML
- 示例说明1
- 示例说明2
XML简介
Xml是一种用于存储和传输数据的标记语言。在Web应用程序中,Xml数据被用于交换数据、配置Web应用程序环境和表示Web应用程序状态等。
Xml文档的结构很类似于HTML,是由标签组成的。Xml文档需要遵循一定的语法规则,否则解析会出现错误。在Xml解析与更新中,Java提供了自带API和第三方库供我们使用。
使用Java自带API解析XML
在Java中,Xml文档的解析可以使用javax的xml.parsers包下的SAXParser和DocumentBuilder等类,也可以使用org.w3c.dom包下的Document接口等。下面是解析Xml并读取其内容的示例代码:
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import org.xml.sax.InputSource;
public class XmlParser {
public void parse(InputStream inputStream) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(inputStream);
Document document = builder.parse(inputSource);
Element rootElement = document.getDocumentElement();
NodeList childNodes = rootElement.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element childElement = (Element) node;
//你的代码逻辑
}
}
}
}
使用第三方库解析XML
除了Java自带的Xml解析API外,我们还可以使用像DOM4J、JDOM、XStream等第三方Xml解析库来解析Xml。这些库都提供了比Java自带API更为易用、更加灵活的Xml解析方式。比如下面是使用DOM4J库来解析Xml的代码示例:
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.List;
public class XmlParser {
public void parse(InputStream inputStream) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
Element rootElement = document.getRootElement();
List<Element> elements = rootElement.elements();
for (Element element : elements) {
//你的代码逻辑
}
}
}
使用Java自带API更新XML
在Java中,更新Xml文档也可以使用javax.xml.transform包下的Transformer和TransformerFactory类。下面是向Xml文档中添加一个新的节点的示例代码:
import javax.xml.transform.Transformer;
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 java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
public class XmlUpdater {
public void update() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new File("example.xml"));
Element newElement = document.createElement("newNode");
newElement.appendChild(document.createTextNode("newNode content"));
XPath xPath = XPathFactory.newInstance().newXPath();
Element parentNode = (Element) xPath.evaluate("/root", document, XPathConstants.NODE);
parentNode.appendChild(newElement);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File("example.xml"));
transformer.transform(source, result);
}
}
使用第三方库更新XML
和解析Xml一样,我们同样可以使用像DOM4J、JDOM、XStream等第三方Xml库来更新Xml文档。比如下面是使用DOM4J库来向Xml文档中添加一个新的节点的示例代码:
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import java.io.FileOutputStream;
import java.io.IOException;
public class XmlUpdater {
public void update() throws IOException, DocumentException {
Document document = DocumentHelper.createDocument();
Element rootElement = DocumentHelper.createElement("root");
document.add(rootElement);
Element newNode = rootElement.addElement("newNode");
newNode.setText("newNode content");
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setEncoding("UTF-8");
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("example.xml"), outputFormat);
xmlWriter.write(document);
xmlWriter.close();
}
}
示例说明1
假设我们有如下Xml文档:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<user id="1">
<name>张三</name>
<gender>男</gender>
<age>20</age>
</user>
<user id="2">
<name>李四</name>
<gender>女</gender>
<age>25</age>
</user>
</root>
我们想解析它并读取其中每个user节点中的信息,可以使用像DOM4J、JDOM、XStream等第三方库解析Xml,也可以使用Java自带API解析Xml文档。最终我们可以将解析得到的每个user节点信息打印出来。比如使用Java自带API解析Xml的示例代码:
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import org.xml.sax.InputSource;
public class XmlParser {
public void parse(InputStream inputStream) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(inputStream);
Document document = builder.parse(inputSource);
Element rootElement = document.getDocumentElement();
NodeList childNodes = rootElement.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element userElement = (Element) node;
String id = userElement.getAttribute("id");
String name = userElement.getElementsByTagName("name").item(0).getTextContent();
String gender = userElement.getElementsByTagName("gender").item(0).getTextContent();
String age = userElement.getElementsByTagName("age").item(0).getTextContent();
System.out.println("id: " + id + ", name: " + name + ", gender: " + gender + ", age: " + age);
}
}
}
}
示例说明2
假设我们有如下Xml文档:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<user id="1">
<name>张三</name>
<gender>男</gender>
<age>20</age>
</user>
<user id="2">
<name>李四</name>
<gender>女</gender>
<age>25</age>
</user>
</root>
我们想向Xml文档中添加一个新的user节点,可以使用像DOM4J、JDOM、XStream等第三方库或Java自带API来更新Xml文档。最终我们可以在Xml文档中添加一个新的user节点。比如使用Java自带API更新Xml的示例代码:
import javax.xml.transform.Transformer;
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 java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
public class XmlUpdater {
public void update() throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new File("example.xml"));
Element newUser = document.createElement("user");
newUser.setAttribute("id", "3");
Element name = document.createElement("name");
name.appendChild(document.createTextNode("王五"));
newUser.appendChild(name);
Element gender = document.createElement("gender");
gender.appendChild(document.createTextNode("男"));
newUser.appendChild(gender);
Element age = document.createElement("age");
age.appendChild(document.createTextNode("30"));
newUser.appendChild(age);
XPath xPath = XPathFactory.newInstance().newXPath();
Element parentNode = (Element) xPath.evaluate("/root", document, XPathConstants.NODE);
parentNode.appendChild(newUser);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File("example.xml"));
transformer.transform(source, result);
}
}
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:基于Java实现XML文件的解析与更新 - Python技术站