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.