【发布时间】:2021-08-01 10:01:52
【问题描述】:
我需要读取一个大约 1MB 的巨大 XML 文件,并且只修改其中的一小部分,而无需编组完整的 XML 文件。 示例:
<student id = "10">
<age>11</age>
<name>Tom</name>
<address>Address Line 1</address>
<phone>1234567890</phone>
<city>NY</city>
<zip>567890</zip>
<postal>12345</postal>
</student>
从上面的 XML 中,我只想读取地址元素并更新,保持其他元素不变。 所以上面的XML应该变成:
<student id = "10">
<age>11</age>
<name>Tom</name>
<address>Updated Address</address>
<phone>1234567890</phone>
<city>NY</city>
<zip>567890</zip>
<postal>12345</postal>
</student>
但是,我在丢失其他元素的地方低于 XML:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<student>
<address>Updated Address</address>
</student>
我正在尝试通过以下代码使用 JAXB:
// we need a blank document to store final xml output
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document document = docBuilder.parse("student.xml");
// create JAXBContext which will be used to create a Binder
JAXBContext jc = JAXBContext.newInstance(Student.class);
Binder<Node> binder = jc.createBinder();
// set output as formatted one
binder.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// get xml node from the document
Node xmlNode = document.getDocumentElement();
// Returns the updated JAXB object
Student st = (Student) binder.updateJAXB(xmlNode);
//Update Address
st.setAddress("Updated Address");
// update xml node with new data
xmlNode = binder.updateXML(st);
// set node value to the document
document.setNodeValue(xmlNode.getNodeValue());
// finally print the edited object on stdout
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.transform(new DOMSource(document), new StreamResult(System.out));
@XmlRootElement
public class Student{
public String getAddress() {
return address;
}
@XmlElement
public void setAddress(String address) {
this.address = address;
}
String address;
}
可以使用哪种 Java 解析机制来实现这一点?还有哪一个在内存和时间方面效率更高?
【问题讨论】:
-
更高效、更野蛮的速度:基于 SAX 的解析。无论如何,1MB 的 XML 并不是一个巨大的 XML。您甚至可以为此使用 XQuery,这是较慢的选择。