Created
November 13, 2012 09:58
-
-
Save samiron/4064964 to your computer and use it in GitHub Desktop.
Jaxp Parsing Examples
This file contains hidden or 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 test.xml; | |
| import java.io.InputStream; | |
| 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; | |
| public class JaxpParsing { | |
| public static void main(String[] args) { | |
| try { | |
| InputStream ins = JaxpParsing.class.getClassLoader().getResourceAsStream("staff_list .xml"); | |
| DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); | |
| DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); | |
| // Document doc = dBuilder.parse(fXmlFile); | |
| Document doc = dBuilder.parse(ins); | |
| 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); | |
| if (nNode.getNodeType() == Node.ELEMENT_NODE) { | |
| Element eElement = (Element) nNode; | |
| System.out.println("First Name : " + getTagValue("firstname", eElement)); | |
| System.out.println("Last Name : " + getTagValue("lastname", eElement)); | |
| System.out.println("Nick Name : " + getTagValue("nickname", eElement)); | |
| System.out.println("Salary : " + getTagValue("salary", eElement)); | |
| } | |
| } | |
| } | |
| 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(); | |
| } | |
| } |
This file contains hidden or 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
| <?xml version="1.0"?> | |
| <company> | |
| <staff> | |
| <firstname>yong</firstname> | |
| <lastname>mook kim</lastname> | |
| <nickname>mkyong</nickname> | |
| <salary>100000</salary> | |
| </staff> | |
| <staff> | |
| <firstname>low</firstname> | |
| <lastname>yin fong</lastname> | |
| <nickname>fong fong</nickname> | |
| <salary>200000</salary> | |
| </staff> | |
| </company> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment