开发者

Is XPath a better a way to read configuration file than using SAX / DOM parsers?

Is XPath a better way to read configuration file than DOM and SAX?

If yes,

Why does not log4j uses XPathExpression 开发者_开发技巧to read configuration file?

If No,

What method should I choose so that I do not have to modify the code if my configuration file changes?

Update: @kdgregory

Normally you are aware of the parameter you are seeking in a configuration file (even the complete path to the node). Why not use XPathExpression in that case? Does that makes processing slow as every time background parsing takes place?


Why does not log4j uses XPathExpression to read configuration file?

Partly because XPath wasn't part of the JDK until 1.5, and Log4J's XML configuration predates that release.

But probably more because the Log4J configuration file is a simple hierarchical structure, and it's easy to traverse such a structure and set configuration options. If you look at the source code for org.apache.log4j.xml.DOMConfigurator, you'll see a very short dispatch loop that looks at the element name hands it off to an object-specific parser.

Is XPath a better way to read configuration file than DOM and SAX?

XPath is not a replacement for DOM and SAX, it's an additional layer on top of them. Yes, you can pass any InputSource to XPathExpression, and you can create an InputSource from any InputStream, but then the parsing happens behind the scenes. And if you have to execute multiple XPath expressions over the same file, it makes a lot of sense to parse it once into a DOM.

What method should I choose so that I do not have to modify the code if my configuration file changes?

Configuration files normally change because your code changes, not the other way around: you add a feature that you want to configure, and then write the code to configure it.

So, when should XPath be used? Where it has more advantage?

One good use for XPath is when you need to extract specific pieces out of a file, particularly if the order in which you extract them does not correspond to the file's document order.


And finally: I strongly recommend using Apache Digester, or any of a number of Java->XML serialization libraries, rather than explicit XPath.


I find XPath useful when I only want a few pieces of information from a complicated document, and don't want to bother dealing with the whole structure. For example, you can select elements in a web page with XPath expressions when using the selenium testing framework.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜