Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
751 views
in Technique[技术] by (71.8m points)

xml - Can SAX Parsers use XPath in Java?

I'm trying to migrate one of my classes which uses DOM parsing with lots of XPath expressions to SAX parsing. DOM Parsing was good for me but some of the files i try to parse are too big and they cause server timeouts. I want to reuse the XPath with the SAX parsing but i'm not sure if it is possible and if not possible could you please help me because i have no idea how the following code will be when i use only SAX:

Document doc = bpsXml.getDocument();
String supplierName = BPSXMLUtils.getXpathString(doc, "/Invoice/InvoiceHeader/Party[@stdValue='SU']/Name/Name1");
String language = BPSXMLUtils.getXpathString(doc, "/Invoice/InvoiceHeader/InvoiceLanguage/@stdValue");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply using a SAX parser will not build a representation of your XML tree in memory (this is why SAX is more memory-efficient). It will only trigger "events" whenever a new XML element is encountered. You will have to keep the context (often a stack of parent elements) in memory to "know" where you are in the tree.

Since you will not have a tree in memory, you will not be able to use XPath. You can only test for the current "context" (your manuallay managed stack) to query your document.Remember that the SAX parser will only do one run on your file, so order in the file is important.

Fortunately, there are other approach like VTD-XML which is a library that build the XML tree in memory, but only the structure part, it does not extract the actual content from the file, the content is extracted as-needed. It is much more memory efficient than a DOM parser while still allowing XPath. I personnaly use this library at work to parse ~700MB XML files with XPath (yes that's insane but it works and it is very fast.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...