我基本上遵循这里的示例
http://www.mkyong.com/java/how-to-read-xml-file-in-java-jdom-example/
所以不要做类似的事情
node.getChildText("firstname")
对吗?
这很好用..
但是有没有办法获取所有“键”,然后我可以查询它来获取值? 就像我们解析 json 一样..
JSONObject json = (JSONObject) parser.parse(value);
for (Object key : json.keySet()) {
Object val = json.get(key);
}
而不是硬编码键和值?
谢谢
Code for reference:
package org.random_scripts;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
public class XMLReader {
public static void main(String[] args) {
SAXBuilder builder = new SAXBuilder();
File xmlFile = new File("data.xml");
try {
Document document = (Document) builder.build(xmlFile);
Element rootNode = document.getRootElement();
List list = rootNode.getChildren("staff");
List children = rootNode.getChildren();
System.out.println(children);
for (int i = 0; i < list.size(); i++) {
Element node = (Element) list.get(i);
System.out.println("First Name : " + node.getChildText("firstname"));
System.out.println("Last Name : " + node.getChildText("lastname"));
System.out.println("Nick Name : " + node.getChildText("nickname"));
System.out.println("Salary : " + node.getChildText("salary"));
}
} catch (IOException io) {
System.out.println(io.getMessage());
} catch (JDOMException jdomex) {
System.out.println(jdomex.getMessage());
}
}
}
最佳答案
好吧,如果你想写出该节点的所有子节点,你可以这样做:
List children = rootNode.getChildren();
for (int i = 0; i < list.size(); i++) {
Element node = (Element) list.get(i);
List dataNodes = node.getChildren();
for (int j = 0; j < dataNodes.size(); ++j) {
Element dataNode = (Element) dataNodes.get(j);
System.out.println(dataNode.getName() + " : " + dataNode.getText());
}
}
这可以让您在不知道名称的情况下写出所有子项,唯一的缺点是您不会为字段提供“漂亮”的名称(即“名字”而不是“名字”)。当然,你在 JSON 中也会有同样的限制 - 我不知道有什么简单的方法可以为字段获取漂亮的名称,除非你的程序对子项有一些了解,这就是你似乎正在尝试的事情以避免。
关于java - 在java中获取给定xml的所有子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18776408/