728x90
반응형
package egovframework.rte.kr.go.test; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DOMReadSample { public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { // XML 문서를 파싱 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); // Document document = documentBuilder.parse("src/sample.xml"); Document document = documentBuilder.parse("src/main/java/egovframework/rte/kr/go/archives/test/javarecipe/chapter08/recipe243/sample.xml"); // 루트 요소 구하기 Element root = document.getDocumentElement(); // 루트 요소 속성 구하기 System.out.println("도서명: " + root.getAttribute("name")); System.out.println("출판사: " + root.getAttribute("publisher")); // 루트 요소의 자식노드 구하기 NodeList children = root.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node node = children.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; if (element.getNodeName().equals("author")) { System.out.println("저자: " + element.getAttribute("name")); } } } } }
<?xml version="1.0"?> <book name="Java역방향 레시피" publisher="정보"> <author name="김은철" /> <author name="유세라" /> <author name="홍길동" /> <author name="홍길순" /> </book>
728x90
반응형