下面是本地XML文件 如何從XML獲得的Java
<configuration>
<property>
<name>test</name>
<value>A</value>
</property>
</configuration>
我如何在Java中的值「A」閱讀的內容是什麼? 下面是我在Java測試
Properties properties = new Properties();
FileInputStream fis = new FileInputStream("path to file");
properties.load(fis);
String test = properties.getProperty("test");
System.out.println(test);
與Java代碼中的問題的代碼?我似乎無法將名稱與價值聯繫起來。此外,由於真實文件包含多對名稱值,因此我無法讀取屬性值。
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());
}
}
}
}
https://stackoverflow.com/questions/7704827/java-reading-xml-file – Aquaballin
我讀過,但在例子中,他們有獨特的用戶和傳遞領域。我的示例中的名稱/值字段重複。 –