0

I need to read data from xml file Dynamically.I had 70 tag names to read and store the data in form of row's. by looking the above code I can read data as i want but how can i write all the tagnames manually using getTagValue(,), how can I retrieve data dynamically into getTagValue(,). I posted some code which I have tried in the above link

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

Community
  • 1
  • 1

1 Answers1

0

Is there any way to generate the tag names dynamically into private static String getTagValue(String sTag, Element eElement) "stag" instead of declaring manually "firstName","lastName","nickName","Salary" into

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

Hear i declared 4 TagNames, if i have 150 tag Names its really Hard Code to write the 150 TagNames manually.is there way to generate "stag" dynamilcally