Reputation: 109
Below are the contents of the local xml file
<configuration>
<property>
<name>test</name>
<value>A</value>
</property>
</configuration>
How can I read in the value "A" in java? Here is the code that I am testing with in Java
Properties properties = new Properties();
FileInputStream fis = new FileInputStream("path to file");
properties.load(fis);
String test = properties.getProperty("test");
System.out.println(test);
Is the problem with the java code? I can't seem to associate the name with the value. Moreover, I can't read the attribute value because of the fact that the real file contains multiple pairs of name-values.
File file = new File("path to file");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document dom = documentBuilder.parse(file);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getChildNodes();
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> values = new ArrayList<String>();
if (nl != null) {
int length = nl.getLength();
for (int i = 0; i < length; i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("configuration")) {
names.add( el.getElementsByTagName("name").item(0).getTextContent());
System.out.println(el.getElementsByTagName("name").item(0).getTextContent());
values.add( el.getElementsByTagName("value").item(0).getTextContent());
System.out.println(el.getElementsByTagName("value").item(0).getTextContent());
}
}
}
}
Upvotes: 0
Views: 2413
Reputation: 575
You could do somthing like this:
File file = new File("path to file");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
document.getDocumentElement().normalize();
Element docEle = document.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("property");
ArrayList names = new ArrayList();
ArrayList values = new ArrayList();
if (nl != null) {
int length = nl.getLength();
//System.out.println(length);
for (int i = 0; i < length; i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("property")) {
names.add( el.getElementsByTagName("name").item(0).getTextContent());
//System.out.println(el.getElementsByTagName("name").item(0).getTextContent());
values.add( el.getElementsByTagName("value").item(0).getTextContent());
//System.out.println(el.getElementsByTagName("value").item(0).getTextContent());
}
}
}
}
This will add all the values into ArrayLists and then you can access them however you want. Or you can print them like the comments I left.
Upvotes: 1