考虑以下具有500 MB数据的XML
<?xml version="1.0" encoding="UTF-8"?>
<Parents>
<process Child ="A">...</process>
<process Child="B">...</process>
<process Child="A">...</process>
<process Child="C">..</process>
<process Child=...
</process>
<\Parents>
此xml具有多个带有标记“ A”或“ B”或其他标记的子属性,我想为“ A”,“ B”,“ C”或其他诸如expamle_A.xml,example_B.xml等创建单独的XML.正在为每个子属性创建单独的xml敌人,这意味着如果我们有500个子属性,则其将创建500个xml.
public static void main(String args[]) {
try {
VTDGen v = new VTDGen();
if (v.parseFile("C:\\..\\example.xml", true)) {
VTDNav vn = vg.getNav();
Autopilot ap = new Autopilot(vn);
ap.selectXPath("/Parents/child");
int chunk = 0;
while (( ap.evalXPath()) != -1) {
long frag = vn.getElementFragment();
(new FileOutputStream("C:\\....\\result" + chunk + ".xml")).write(vn.getXML().getBytes(), (int) frag,
(int) (frag >> 32));
chunk++;
}
}
} catch (Exception ex) {
ex.printstacktrace();
}
}
现在的事情是,我想基于实例的同一组的子对象属性拆分文件,“ A”的所有子对象都应以相同的方式在example_A.xml文件中用于B,C和其他.
解决方法:
这是对现有代码的非常简单的修改.实际上,有多种方法可以做到这一点.我只是向您展示其中之一:通过使用VTDNav的getAttrVal method()显式比较attr val.
public static void main1(String args[]) {
try {
VTDGen vg = new VTDGen();
if (vg.parseFile("C:\\..\\example.xml", true)) {
VTDNav vn = vg.getNav();
Autopilot ap = new Autopilot(vn);
ap.selectXPath("/Parents/process");
int chunk = 0;
FileOutputStream fopsA=(new FileOutputStream("C:\\....\\resultA" + chunk + ".xml"));
fopsA.write("<Parent>\n".getBytes());
FileOutputStream fopsB=(new FileOutputStream("C:\\....\\resultB" + chunk + ".xml"));
while (( ap.evalXPath()) != -1) {
long frag = vn.getElementFragment();
int i=vn.getAttrVal("Child");
if (i==-1) throw new NavException("unexpected result");
if (vn.comparetokenString(i,"A")==0){
fopsA.write(vn.getXML().getBytes(), (int) frag,
(int) (frag >> 32));
}else if (vn.comparetokenString(i,"B")==0){
fopsB.write(vn.getXML().getBytes(), (int) frag,
(int) (frag >> 32));
}
chunk++;
}
fopsA.write("</Parent>\n".getBytes());
fopsB.write("</Parent>\n".getBytes());
}
} catch (Exception ex) {
ex.printstacktrace();
}