Hi,
I'm only a few days old to Java, and trying to become familiar with its
ins and outs. I'm trying to write a routine to load a simple XML
configuration file:
<root>
<database>
<host>thehost</host>
<user>theuser</user>
<password>mypassword</password>
</database>
</root>
class blah {
private static String configFilename = "agentProfiler.conf.xml";
private static String dbHost, dbUser, dbPass;
...
public static void loadConfiguration() {
XPath xpath = XPathFactory.newInstance().newXPath();
InputSource inputSource = null;
try {
inputSource = new InputSource(new FileInputStream(configFilename));
} catch (FileNotFoundException e) {
System.out.println("Configuration file " + configFilename + "
not found.");
System.exit(-1);
}
try {
dbHost = xpath.evaluate("/root/database/host", inputSource);
dbPass = xpath.evaluate("/root/database/password", inputSource);
System.out.println("host=" + dbHost);
System.out.println("user=" + dbUser);
} catch (XPathExpressionException e) {
System.out.println("Couldn't parse the configuration file. You
may have an error in your syntax.");
e.printStackTrace();
System.exit(-1);
}
}
...
}
The problem I'm having is that the first xpath expression evaluates
fine. Any subsequent expression throws an IOException (by way of
XPathExpressionException) that it can't find the file. Are InputSource's
one-time use only, or is there something I'm missing?
Also, I'm trying to pin down exactly how try/catch blocks should look
with regards to declarations and such. (E.g., if I decided to declare
inputSource inside the try/catch, Java complains it can't find the
variable if I want to use it outside the block later, which I'm betting
is a scope issue. But if I don't 'null' it beforehand, Java complains it
may not be initialized. What's the proper way to do this?)
Thanks much for any help.
- Josh
Eric Olander - 21 Jun 2005 22:57 GMT
The approach I'd take is to use SAX or DOM to read this XML file - SAX if it
really is as simple as you show, DOM if it's bigger and you want to make
XParth queries against it. The results you are getting make sense with the
approach you are taking. XPath is going to go over the entire document to
resolve your query. You'd need to reset your InputSource between subsequent
queries. You are seeing scoping issues with the try/catch behaviour you
describe. Anything you need access to outside of a try/catch needs to be
declared beforehand and set to some default value (null or otherwise).
-Eric
SCJP, SCJD
> Hi,
>
[quoted text clipped - 62 lines]
>
> - Josh