Created
July 13, 2016 10:30
-
-
Save sunmeat/b73c98307fff132fbffc8afd08c2b7c5 to your computer and use it in GitHub Desktop.
dom parsing 1 java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package xml; | |
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; | |
import java.io.IOException; | |
import javax.xml.parsers.ParserConfigurationException; | |
import org.w3c.dom.DOMException; | |
import org.xml.sax.SAXException; | |
public class Program { | |
public static void main(String argv[]) { | |
try { | |
File fXmlFile = new File("C:\\1\\xml.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 (ParserConfigurationException | SAXException | IOException | DOMException e) { | |
System.out.println("Smth wrong!"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment