我需要动态地从 xml 文件中读取数据。我有 70 个标签名称以行的形式读取和存储数据。通过查看上面的代码,我可以根据需要读取数据,但是如何使用 getTagValue( , ) 手动编写所有标记名,如何将数据动态检索到 getTagValue( , ) 中。我在上面的链接中发布了一些我尝试过的代码
public class ParseXML {
public static void main(String argv[]) {
try {
File fXmlFile = new File("data/Hotel.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println(doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("-----------------------");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String firstname=getTagValue("firstname", eElement);
String lastName=getTagValue("lastname", eElement);
String nickname=getTagValue("nickname", eElement);
String salary=getTagValue("salary", eElement);
System.out.println(firstname+" ," + lastName+" ," + nickname+" ," + salary);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
}