Answers for "java xml reader"

0

java read xml

String dir = System.getProperty("user.dir");
File inputFile = new File(dir + File.separator + "dats.xml");
DocumentBuilderFactory dbFactory =
	DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
/*
Elimina nodos vacíos y combina adyacentes en caso de que los
hubiera
*/
Posted by: Guest on March-05-2021
0

java xml reader

package com.mkyong.seo;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

  public static void main(String argv[]) {

    try {

    File fXmlFile = new File("/Users/mkyong/staff.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
            
    //optional, but recommended
    //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
            
    NodeList nList = doc.getElementsByTagName("staff");
            
    System.out.println("----------------------------");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);
                
        System.out.println("\nCurrent Element :" + nNode.getNodeName());
                
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element eElement = (Element) nNode;

            System.out.println("Staff id : " + eElement.getAttribute("id"));
            System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
            System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
            System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
            System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

        }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
  }

}
Posted by: Guest on November-07-2020

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language