使用Java解析多个离散的自定义XML文档的最佳方法是什么?
使用Java解析多个离散的自定义XML文档的最佳方法是什么?
另一个非常有用的XML解析方法,虽然比这些方法稍微新一些,并且仅在Java6之后的JRE中包含,是StAX。 StAX被构思为DOM的基于树状结构和SAX的基于事件的方法之间的媒介方法。它与SAX非常相似,因为解析非常大的文档很容易,但在这种情况下,应用程序从解析器“拉”信息,而不是解析器将事件“推送”到应用程序。您可以在此处找到有关此主题的更多解释。
因此,根据您想要实现的目标,可以使用其中一种方法。
使用 dom4j 库
首先阅读文档
import java.net.URL;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
public class Foo {
public Document parse(URL url) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(url);
return document;
}
}
public void get_author(Document document) {
Node node = document.selectSingleNode( "//AppealRequestProcessRequest/author" );
String author = node.getText();
return author;
}
您需要使用org.xml.sax.XMLReader
(http://docs.oracle.com/javase/7/docs/api/org/xml/sax/XMLReader.html)。
import com.ximpleware.*;
public class extractValue{
public static void main(String s[]) throws VTDException, IOException{
VTDGen vg = new VTDGen();
if (!vg.parseFile("input.xml", false));
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/aa/bb[name='k1']/value");
int i=0;
while ((i=ap.evalXPath())!=-1){
System.out.println(" value ===>"+vn.toString(i));
}
}
}