示例 XML
<?xml version="1.0" encoding="UTF-8"?>
<Document>
<Report>
<Node>
<Detail>
<Id>1</Id>
<Value>Value 1</Value>
<Tag1>
<Owner>
<Id>
<INT>12345</INT>
</Id>
</Owner>
</Tag1>
</Detail>
<Status>
<Result>Pass</Result>
</Status>
</Node>
<Node>
<Detail>
<Id>2</Id>
<Value>Value 2</Value>
<Tag1>
<Owner>
<Id>
<String>TEST</String>
</Id>
</Owner>
</Tag1>
</Detail>
<Status>
<Result>Fail</Result>
</Status>
</Node>
<Node>
<Detail>
<Id>3</Id>
<Value>Value 3</Value>
<Tag1>
<Owner>
<Id>
<UN>UNKNOWN</UN>
</Id>
</Owner>
</Tag1>
</Detail>
<Status>
<Result>Waiting</Result>
</Status>
</Node>
</Report>
</Document>
基于上述结构,我想读取元素/属性并填充 POJO(最好是 XPath),因为元素路径不一致,例如:<Tag1>
.
我不知道如何继续。我尝试过使用 AutoPilot,但它按顺序读取数据,例如所有节点 ID。我无法找到读取 <Node>
内所有数据的方法然后继续进行下一项,依此类推。最后我需要返回填充的 POJO 集合。
DOM 超出了范围,因为 XML 文件很大,大小几乎为 800MB 到 1GB,大约为 1GB。 600,000+ <Node>
.
提前致谢。
XML 阅读器
公共(public)无效过程(最终字符串完整路径){
try {
final VTDGen vg = new VTDGen();
if (vg.parseFile(fullPath, false)) {
final VTDNav vn = vg.getNav();
final AutoPilot ap = new AutoPilot(vn);
ap.selectXPath(ROOT);
while ((ap.evalXPath()) != -1) {
final AutoPilot pilot1 = new AutoPilot(vn);
pilot1.selectXPath(ROOT + "/Detail/Id");
while (pilot1.evalXPath() != -1) {
final int t = vn.getText();
if (t != -1) {
System.out.println(vn.toNormalizedString(t));
}
final AutoPilot pilot2 = new AutoPilot(vn);
pilot2.selectXPath(ROOT + "/Status/Result");
if (pilot2.evalXPath() != -1) {
final int k = vn.getText();
if (k != -1) {
System.out.println(vn.toNormalizedString(k));
}
}
// pilot2.resetXPath();
}
}
}
}
catch (Exception exception) {
}
}
最佳答案
我稍微修改了你的代码以使其正常工作...加上更正了一些事情...将在代码中嵌入更多注释...
一些需要记住的事情
- 永远不要在一段时间内进行 autoPIlot 实例化和 xpath 选择 环形。从来没有!
- 通过resetXPath()重用
- 使用push和pop来维持最外层while循环中的一致状态。
导入 com.ximpleware.*; 公开课萨维{
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
final VTDGen vg = new VTDGen();
if (vg.parseFile("d:\\xml\\sawi.xml", false)) {
final VTDNav vn = vg.getNav();
final AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/Document/Report/Node");
final AutoPilot pilot1 = new AutoPilot(vn);
pilot1.selectXPath("Detail/Id");
final AutoPilot pilot2 = new AutoPilot(vn);
pilot2.selectXPath("Status/Result");
while ((ap.evalXPath()) != -1) {
vn.push();
while (pilot1.evalXPath() != -1) {
final int t = vn.getText();
if (t != -1) {
System.out.println(vn.toNormalizedString(t));
}
}
vn.pop();
vn.push();
if (pilot2.evalXPath() != -1) {
final int k = vn.getText();
if (k != -1) {
System.out.println(vn.toNormalizedString(k));
}
}
vn.pop();
pilot2.resetXPath();
pilot1.resetXPath();
// vn.pop();
}
}
}
}
关于java - 使用 VTD-XML 从 XML 填充 POJO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52388317/