[英]Modify all values found by xPath Expression in huge xml file with VTD-XML and Java
在网上进行了大量研究之后,我决定使用Java Api VTD-XML来组合巨大的xml文件,进行解析和编辑以及xPath
要修改的XML文件为10 MB-400 MB,如下所示:
<?xml version="1.0" encoding="ISO-8859-9"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Scheme.xsd">
<Book>
<BookInfo>
<Novel>
<NovelTitle>abc</NovelTitle>
<Author>def</Author>
<Address>
<LastName>ghi</LastName>
<FirstName>jklm<FirstName>
</Address>
<Address>
<LastName>opqr</LastName>
<FirstName>stuv</FirstName>
</Address>
<Customer>
<CustomerNumber>1000</CustomerNumber>
<Address>
<LastName>wxy</LastName>
<FirstName>zzzz</FirstName>
</Address>
<Address>
<LastName>aaaaa</LastName>
<FirstName>bbbb</FirstName>
</Address>
</Customer>
.
.
.
</Novel>
</BookInfo>
</Book>
请不要开始讨论结构和元素名称。 我无法改变。
我想编辑文件中与某个xPath表达式匹配的所有出现的元素值。 当我为此使用VTD XML和XPath时,在生成的文档中,仅正确更改了一个元素值。 我的代码:
static VTDGen vg = new VTDGen();
static String inFile = "books.xml";
static XMLModifier xm = new XMLModifier();
public static void main(String[] args) throws Exception{
getNodesFromDocument();
}
private static void getNodesFromDocument() throws ParseException, NavException, XPathParseException, XPathEvalException, Exception {
int result;
AutoPilot ap = new AutoPilot();
ap.selectXPath("//Address[LastName='ghi']/FirstName/text()");
if (vg.parseFile(inFile,true)){
VTDNav vn = vg.getNav();
ap.bind(vn);
while((result = ap.evalXPath())!=-1){
//System.out.println(vn.getText() + vn.toString(result));
modifyNodes(vn, result);
}
}
xm.output(new FileOutputStream("resultbooks.xml"));
}
private static void modifyNodes(VTDNav vn, int line) throws Exception{
// instantiate VTDGen and XMLModifier
xm.bind(vn);
// update the text content
if (line!=-1){
xm.updateToken(line,"TestValue");
}
}
}
我想编辑文档中// Address [LastName ='ghi'] / FirstName / text()的所有值,因此
jkl
.
.
.
getNodesFromDocument()中的while循环正确显示了所有值,但并非所有值都被修改。 只有一个
<LastName>ghi</LastName>
<FirstName>TestValue<FirstName>
出现在输出文件中。 您能帮我找到解决问题的方法吗? 代码有什么问题? 为什么输出中只有一个修改值?
谢谢你的帮助!
textValue仅出现一次的原因是因为XMLModifier的bind进行了大量的初始化和状态清理,实际上清除了之前发生的所有更新/删除……您需要做的是每次都不在您的私有方法中绑定它” ModifyNode”,而是将绑定移到主节点中...它将起作用...请参见下面的代码
static VTDGen vg = new VTDGen();
static String inFile = "c:\\xml\\kepler.xml";
static XMLModifier xm = new XMLModifier();
/**
* @param args
*/
public static void main(String[] args) throws ParseException, NavException, XPathParseException, XPathEvalException, Exception{
// TODO Auto-generated method stub
int result;
AutoPilot ap = new AutoPilot();
ap.selectXPath("//Address[LastName='ghi']/FirstName/text()");
if (vg.parseFile(inFile,true)){
VTDNav vn = vg.getNav();
ap.bind(vn);xm.bind(vn);
while((result = ap.evalXPath())!=-1){
//System.out.println(vn.getText() + vn.toString(result));
xm.updateToken(result,"TestValue");
}
}
xm.output(new FileOutputStream("c:\\xml\\resultbooks.xml"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.