Источник
iblog.xml
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <blogs> <blog id="1"> <author>Pavel</author> <language>Java</language> </blog> <blog id="2"> <author>Mat</author> <language>C#</language> </blog> </blogs> |
Main.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Node; import java.io.File; import java.io.IOException; /** * Created by Николай on 03.12.2015. */ public class Main { public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException { File xmlFile = new File("D:\JAVA\DOM_XML_PARSER\src\iblog.xml"); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(xmlFile); document.getDocumentElement().normalize(); System.out.println("Корневой элемент: " + document.getDocumentElement().getNodeName()); NodeList nodeList = document.getElementsByTagName(document.getDocumentElement().getChildNodes().item(1).getNodeName()); System.out.println("--------------------"); for (int tmp = 0; tmp < nodeList.getLength(); tmp++) { Node node = nodeList.item(tmp); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; System.out.println("Blog #" + tmp + ":"); System.out.println("Author: " + element.getElementsByTagName("author").item(0).getChildNodes().item(0).getNodeValue()); System.out.println("Language: " + element.getElementsByTagName("language").item(0).getChildNodes().item(0).getNodeValue()); } } } } |