如何从XML文件动态读取数据

时间:2012-08-02 09:11:11

标签: java xml-parsing

我需要动态地从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();
  }

}

How to modify XML data in Dom parser

1 个答案:

答案 0 :(得分:0)

有没有办法动态生成标记名称到私有静态字符串getTagValue(String sTag, Element eElement) "stag",而不是手动将"firstName","lastName","nickName","Salary"声明为

String firstname=getTagValue("firstname", eElement);           
String lastName=getTagValue("lastname", eElement);             
String nickname=getTagValue("nickname", eElement);              
String salary=getTagValue("salary", eElement); 

听到我声明了4个TagNames,如果我有150个标签名称,那么它是真正的硬代码来手动编写150个TagNames。是否可以动态生成“stag”