XML
- eXentsible Markup Language
DOM
- Document Object Model (DOM)
- a platform and language-neutral interface
- that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
- 부모 interface: node
- 자식 interface: attr, element, comment 모두 node~
- 자바에서 모든 객체가 모두 Object = XML에서 모든 객체는 Node
- w3school XML
- java 공식 api
Parsing 방법
- SaX Parsing: 옛날 방법
- DOM Parsing
- 프로그램 시작 동시에 DOM객체가 메모리에 올라감
- 장점: 빠른 속도
- 단점: 메모리 많이 잡아먹음 -> 옛날엔 그래서 SaX방식 썼음
예제: DomParsingTest.java
public class DomParsingTest2 {
public void parsing() {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
String url = getClass()
.getResource("/kr/or/ddit/basic/book.xml")
.toExternalForm();
Document xmlDoc = builder.parse(url);
Element root = xmlDoc.getDocumentElement();
System.out.println("루트 엘리먼트 태그명: " + root.getTagName());
NodeList bookNodeList = root.getElementsByTagName("book");
Node firstBookNode = bookNodeList.item(0);
Element firstBookElement = (Element) firstBookNode;
System.out.println("엘리먼트 객체의 getAttribute() 이용 => " +
firstBookElement.getAttribute("isbn"));
NamedNodeMap nodeMap = firstBookNode.getAttributes();
System.out.println("노드 객체의 getAttributes() 이용 => " +
nodeMap.getNamedItem("isbn"));
NodeList firstBookChildNodeList = firstBookNode.getChildNodes();
Node titleNode = firstBookChildNodeList.item(1);
Element titleElement = (Element) titleNode;
System.out.println("titleElement.getTagName() => " + titleElement.getTagName());
System.out.println("titleElement.getTextContext() => " + titleElement.getTextContent());
System.out.println("-------------------------------------------------------------");
for (int i = 0; i < bookNodeList.getLength(); i++) {
Node bookNode = bookNodeList.item(i);
Element bookElement = (Element) bookNode;
String isbn = bookElement.getAttribute("isbn");
String kind = bookElement.getAttribute("kind");
String title = bookElement.getElementsByTagName("title").item(0).getTextContent();
String author = bookElement.getElementsByTagName("author").item(0).getTextContent();
String price = bookElement.getElementsByTagName("price").item(0).getTextContent();
String str = String.format("%8s %10s %20s %10s %8s", isbn, kind, title, author, price);
System.out.println(str);
}
System.out.println("-------------------------------------------------------------");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new DomParsingTest2().parsing();
}
}