提问人:Jame 提问时间:9/11/2011 最后编辑:SyscallJame 更新时间:11/14/2023 访问量:286351
如何读取和写入XML文件?
How to read and write XML files?
答:
下面是一个快速的 DOM 示例,展示了如何使用其 dtd 读取和写入一个简单的 xml 文件:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE roles SYSTEM "roles.dtd">
<roles>
<role1>User</role1>
<role2>Author</role2>
<role3>Admin</role3>
<role4/>
</roles>
和 DTD:
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT roles (role1,role2,role3,role4)>
<!ELEMENT role1 (#PCDATA)>
<!ELEMENT role2 (#PCDATA)>
<!ELEMENT role3 (#PCDATA)>
<!ELEMENT role4 (#PCDATA)>
首先导入这些:
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
import org.w3c.dom.*;
以下是您将需要的几个变量:
private String role1 = null;
private String role2 = null;
private String role3 = null;
private String role4 = null;
private ArrayList<String> rolev;
下面是一个读取器(字符串 xml 是 xml 文件的名称):
public boolean readXML(String xml) {
rolev = new ArrayList<String>();
Document dom;
// Make an instance of the DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use the factory to take an instance of the document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using the builder to get the DOM mapping of the
// XML file
dom = db.parse(xml);
Element doc = dom.getDocumentElement();
role1 = getTextValue(role1, doc, "role1");
if (role1 != null) {
if (!role1.isEmpty())
rolev.add(role1);
}
role2 = getTextValue(role2, doc, "role2");
if (role2 != null) {
if (!role2.isEmpty())
rolev.add(role2);
}
role3 = getTextValue(role3, doc, "role3");
if (role3 != null) {
if (!role3.isEmpty())
rolev.add(role3);
}
role4 = getTextValue(role4, doc, "role4");
if ( role4 != null) {
if (!role4.isEmpty())
rolev.add(role4);
}
return true;
} catch (ParserConfigurationException pce) {
System.out.println(pce.getMessage());
} catch (SAXException se) {
System.out.println(se.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
return false;
}
这里有一位作家:
public void saveToXML(String xml) {
Document dom;
Element e = null;
// instance of a DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use factory to get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// create instance of DOM
dom = db.newDocument();
// create the root element
Element rootEle = dom.createElement("roles");
// create data elements and place them under root
e = dom.createElement("role1");
e.appendChild(dom.createTextNode(role1));
rootEle.appendChild(e);
e = dom.createElement("role2");
e.appendChild(dom.createTextNode(role2));
rootEle.appendChild(e);
e = dom.createElement("role3");
e.appendChild(dom.createTextNode(role3));
rootEle.appendChild(e);
e = dom.createElement("role4");
e.appendChild(dom.createTextNode(role4));
rootEle.appendChild(e);
dom.appendChild(rootEle);
try {
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
// send DOM to file
tr.transform(new DOMSource(dom),
new StreamResult(new FileOutputStream(xml)));
} catch (TransformerException te) {
System.out.println(te.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
} catch (ParserConfigurationException pce) {
System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
}
}
getTextValue 在这里:
private String getTextValue(String def, Element doc, String tag) {
String value = def;
NodeList nl;
nl = doc.getElementsByTagName(tag);
if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
value = nl.item(0).getFirstChild().getNodeValue();
}
return value;
}
添加一些访问器和变函数,您就完成了!
评论
上面的答案只处理 DOM 解析器(通常读取内存中的整个文件并解析它,对于一个大文件来说是个问题),您可以使用使用更少内存且速度更快的 SAX 解析器(无论如何这取决于您的代码)。
SAX 解析器在找到元素的开头、元素的结尾、属性、元素之间的文本等时会回调一些函数,因此它可以解析文档,同时你 得到你需要的东西。
一些示例代码:
http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
使用 JAXB(用于 XML 绑定的 Java 体系结构)编写 XML:
http://www.mkyong.com/java/jaxb-hello-world-example/
package com.mkyong.core;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
@XmlAttribute
public void setId(int id) {
this.id = id;
}
}
package com.mkyong.core;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBExample {
public static void main(String[] args) {
Customer customer = new Customer();
customer.setId(100);
customer.setName("mkyong");
customer.setAge(29);
try {
File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
答案仅涵盖 DOM/SAX 和 JAXB 示例的复制粘贴实现。
但是,在使用 XML 时缺少一个很大的区域。在许多项目/程序中,需要存储/检索一些基本数据结构。你的程序已经有一个类,用于你漂亮而闪亮的业务对象/数据结构,你只需要一种舒适的方式将这些数据转换为XML结构,这样你就可以对它做更多的魔术(存储、加载、发送、使用XSLT操作)。
这就是XStream的闪光点。只需对保存数据的类进行批注,或者如果不想更改这些类,则配置 XStream 实例以封送(对象 -> xml)或取消编组(xml ->对象)。
在内部,XStream 使用标准 Java 对象序列化的反射、readObject 和 readResolve 方法。
您可以在这里获得一个良好而快速的教程:
为了简要概述它是如何工作的,我还提供了一些示例代码,用于编组和解组数据结构。
编组/解编组全部发生在方法中,其余的只是生成一些测试对象并将一些数据填充到它们的代码。
配置实例非常简单,并且每个实例只需一行代码即可完成编组/解组。main
xStream
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
public class XStreamIsGreat {
public static void main(String[] args) {
XStream xStream = new XStream();
xStream.alias("good", Good.class);
xStream.alias("pRoDuCeR", Producer.class);
xStream.alias("customer", Customer.class);
Producer a = new Producer("Apple");
Producer s = new Producer("Samsung");
Customer c = new Customer("Someone").add(new Good("S4", 10, new BigDecimal(600), s))
.add(new Good("S4 mini", 5, new BigDecimal(450), s)).add(new Good("I5S", 3, new BigDecimal(875), a));
String xml = xStream.toXML(c); // objects -> xml
System.out.println("Marshalled:\n" + xml);
Customer unmarshalledCustomer = (Customer)xStream.fromXML(xml); // xml -> objects
}
static class Good {
Producer producer;
String name;
int quantity;
BigDecimal price;
Good(String name, int quantity, BigDecimal price, Producer p) {
this.producer = p;
this.name = name;
this.quantity = quantity;
this.price = price;
}
}
static class Producer {
String name;
public Producer(String name) {
this.name = name;
}
}
static class Customer {
String name;
public Customer(String name) {
this.name = name;
}
List<Good> stock = new ArrayList<Good>();
Customer add(Good g) {
stock.add(g);
return this;
}
}
}
好的,答案列表中已经有 DOM、JaxB 和 XStream,仍然有一种完全不同的方法来读取和写入 XML: 数据投影 您可以使用一个库来分离 XML 结构和 Java 结构,该库将 XML 数据作为 Java 接口提供可读和可写的视图。从教程中:
给定一些现实世界的 XML:
<weatherdata>
<weather
...
degreetype="F"
lat="50.5520210266113" lon="6.24060010910034"
searchlocation="Monschau, Stadt Aachen, NW, Germany"
... >
<current ... skytext="Clear" temperature="46"/>
</weather>
</weatherdata>
使用数据投影,您可以定义投影接口:
public interface WeatherData {
@XBRead("/weatherdata/weather/@searchlocation")
String getLocation();
@XBRead("/weatherdata/weather/current/@temperature")
int getTemperature();
@XBRead("/weatherdata/weather/@degreetype")
String getDegreeType();
@XBRead("/weatherdata/weather/current/@skytext")
String getSkytext();
/**
* This would be our "sub projection". A structure grouping two attribute
* values in one object.
*/
interface Coordinates {
@XBRead("@lon")
double getLongitude();
@XBRead("@lat")
double getLatitude();
}
@XBRead("/weatherdata/weather")
Coordinates getCoordinates();
}
并像 POJO 一样使用此接口的实例:
private void printWeatherData(String location) throws IOException {
final String BaseURL = "http://weather.service.msn.com/find.aspx?outputview=search&weasearchstr=";
// We let the projector fetch the data for us
WeatherData weatherData = new XBProjector().io().url(BaseURL + location).read(WeatherData.class);
// Print some values
System.out.println("The weather in " + weatherData.getLocation() + ":");
System.out.println(weatherData.getSkytext());
System.out.println("Temperature: " + weatherData.getTemperature() + "°"
+ weatherData.getDegreeType());
// Access our sub projection
Coordinates coordinates = weatherData.getCoordinates();
System.out.println("The place is located at " + coordinates.getLatitude() + ","
+ coordinates.getLongitude());
}
这甚至适用于创建 XML,XPath 表达式可以是可写的。
SAX
解析器与解析器的工作方式不同,它既不会将任何文档加载到内存中,也不会创建文档的任何对象表示形式。相反,解析器使用回调函数来通知客户端文档结构。DOM
XML
XML
SAX
org.xml.sax.helpers.DefaultHandler
XML
SAX
解析器比解析器更快,占用的内存更少。
请参阅以下回调方法:DOM
SAX
startDocument()
和 – 在 XML 文档的开头和结尾调用的方法。 和 – 在文档元素的开头和结尾调用的方法。 – 使用 XML 文档元素的开始和结束标记之间的文本内容调用的方法。endDocument()
startElement()
endElement()
characters()
- XML 文件
创建一个简单的 XML 文件。
<?xml version="1.0"?>
<company>
<staff>
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff>
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>
- XML 解析器:
Java 文件 使用 SAX 解析器解析 XML 文件。
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean bfname = false;
boolean blname = false;
boolean bnname = false;
boolean bsalary = false;
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
System.out.println("Start Element :" + qName);
if (qName.equalsIgnoreCase("FIRSTNAME")) {
bfname = true;
}
if (qName.equalsIgnoreCase("LASTNAME")) {
blname = true;
}
if (qName.equalsIgnoreCase("NICKNAME")) {
bnname = true;
}
if (qName.equalsIgnoreCase("SALARY")) {
bsalary = true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
System.out.println("End Element :" + qName);
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bfname) {
System.out.println("First Name : " + new String(ch, start, length));
bfname = false;
}
if (blname) {
System.out.println("Last Name : " + new String(ch, start, length));
blname = false;
}
if (bnname) {
System.out.println("Nick Name : " + new String(ch, start, length));
bnname = false;
}
if (bsalary) {
System.out.println("Salary : " + new String(ch, start, length));
bsalary = false;
}
}
};
saxParser.parse("c:\\file.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
结果
起始元素:company
起始元素:staff
起始元素:firstname 名字 : yong 结束元素:firstname 起始元素:lastname 姓氏 : mook kim 结束元素:lastname
起始元素:
昵称 : mkyong
结束元素:昵称
等...
来源(MyKong) - http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
这是保存 xml 的示例代码:
public void save(String tableName, List<Customer> customers) {
File f = new File(FileUtil.getTableFileName(tableName));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// make the xml tree
// use factory to get the instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
// Root element <customers>
Element rootElem = doc.createElement(Customer.KEY_ROOT);
doc.appendChild(rootElem);
for (Customer customer : customers) {
Element customerElem = doc.createElement(Customer.KEY_ELEMENT);
rootElem.appendChild(customerElem);
// child element <ID> under <customer>
Element cid = doc.createElement(Customer.KEY_ID);
cid.appendChild(doc.createTextNode(Integer.toString(customer.getId())));
customerElem.appendChild(cid);
if (customer.getName() != null) {
Element name = doc.createElement(Customer.KEY_NAME);
name.appendChild(doc.createTextNode(customer.getName()));
customerElem.appendChild(name);
}
if (customer.getAddress() != null) {
Element address = doc.createElement(Customer.KEY_ADDRESS);
address.appendChild(doc.createTextNode(customer.getAddress()));
customerElem.appendChild(address);
}
if (customer.getCity() != null) {
Element city = doc.createElement(Customer.KEY_CITY);
city.appendChild(doc.createTextNode(customer.getCity()));
customerElem.appendChild(city);
}
if (customer.getPostCode() != null) {
Element postCode = doc.createElement(Customer.KEY_POSTCODE);
postCode.appendChild(doc.createTextNode(customer.getPostCode()));
customerElem.appendChild(postCode);
}
if (customer.getCountry() != null) {
Element country = doc.createElement(Customer.KEY_COUNTRY);
country.appendChild(doc.createTextNode(customer.getCountry()));
customerElem.appendChild(country);
}
}
// save the xml file
// Transformer is for process XML from a variety of sources and write the
// transformation
// output to a variety of sinks
Transformer transformer = TransformerFactory.newInstance().newTransformer();
// set xml encoding to utf-8
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
// pretty print
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(f);
transformer.transform(source, result);
} catch (Exception e) {
e.printStackTrace();
}
}
下面是一个阅读示例:
public static List<List<String>> read(String fileName) {
List<List<String>> result = new ArrayList<>();
File f = new File(fileName);
if (!f.exists()) {
return result;
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
doc.getDocumentElement().normalize();
NodeList StatesNodes = doc.getElementsByTagName(STATE_ROOT_ELEMENT);
List<String> keys = new ArrayList<>();
List<String> states = new ArrayList<>();
for (int i = 0; i < StatesNodes.getLength(); i++) {
NodeList children = StatesNodes.item(i).getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node child = children.item(j);
String childName = child.getNodeName();
if (child.getNodeType() == Node.ELEMENT_NODE) {
keys.add(childName);
states.add(child.getTextContent());
}
}
}
result.add(keys);
result.add(states);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
评论