我有当前的 XML 文件:
<test>
<class name="something" class="some">
<field>
<name>something</name>
<location>Something.class</location>
<desc></desc>
</field>
</class>
</test>
为了解析 XML 文件,我有以下代码:
public static void parse(){
try {
File xml = new File("testfile.xml");
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = db.parse(xml);
NodeList node = document.getChildNodes();
Element root = (Element) node.item(0);
NodeList classes = root.getElementsByTagName("class");
for(int i = 0; i < classes.getLength(); i++){
Node nodes = classes.item(i);
Element classElement = (Element) nodes;
System.out.println("Class name: " + classElement.getAttribute("name"));
System.out.println("Location: " + classElement.getAttribute("class"));
}
} catch (Exception ignored){
}
}
但是我不知道要获取它的子字段元素的值。我只使用以下方法获得了元素:
NodeList classes = root.getElementsByTagName("field");
我的问题是,如何在元素字段中获取这些值?