Skip to main content

DOM XML Parsing, dBuilder.parse(), normalize()

Image result for java dom parser


DOM을 이용하여 XML instance의 일부 데이터 목록을 parsing 해 보았다.

1
2
3
4
5
6
7
8
9
10
public class Ex_xml_parsing {
    public static void main(String[] args) {
        try {
            File xmlFile = new File("D:/Workspace/_JAVA/Ex_xml_parsing/src/test.xml");            
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // instance 생성            
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // builder 생성            
            Document doc = dBuilder.parse(xmlFile); // xml 파일을 dom 객체로 파싱
cs

dBuilder.parse(xmlFile)

DocumentBuilder.parse(File f): Parse the content of the given InputStream as an XML document and return a new DOM Document object. An IllegalArgumentException is thrown if the InputStream is null. throws SAXException, IOException

(XML 문서 컨텐트를 parse해서 DOM 문서 객체로 리턴한다.)

1
doc.getDocumentElement().normalize(); // 파싱한 파일 normalize
cs

doc.getDocumentElement().normalize(): Puts all Text nodes in the full depth of the sub-tree underneath this Node where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes.

This basically means that the following XML element

<foo>hello
wor
ld</foo>
could be represented like this in a denormalized node:

Element foo
    Text node: ""
    Text node: "Hello "
    Text node: "wor"
    Text node: "ld"
When normalized, the node will look like this

Element foo
    Text node: "Hello world"

(<foo>hello
wor
ld</foo>
이런 형태의 코드를 denormalize된 노드로 표현하면:

Element foo
    Text node: ""
    Text node: "Hello "
    Text node: "wor"
    Text node: "ld"
normalize하면

Element foo
    Text node: "Hello world"
이렇게 된다.)


- 전체 코드

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
/*
DOM XML Parser Example
Ref - http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
*/
public class Ex_xml_parsing {
    public static void main(String[] args) {
        try {
            File xmlFile = new File("D:/Workspace/_JAVA/Ex_xml_parsing/src/test.xml");            
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // instance 생성            
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // builder 생성            
            Document doc = dBuilder.parse(xmlFile); // xml 파일을 dom 객체로 파싱
            doc.getDocumentElement().normalize(); // 파싱한 파일 normalize
            // 루트 element(최상위 노드)의 이름 출력
            System.out.println("Root element :" + doc.getDocumentElement().getNodeName());             
            System.out.println("\n");           
            // staff라는 이름을 가진 element를 모두 찾아 NodeList로 리턴 
            NodeList nList = doc.getElementsByTagName("staff"); 
            // 리스트의 길이 만큼 출력            for (int temp = 0; temp < nList.getLength(); temp++) {
                Node nNode = nList.item(temp); // NodeList.item(int index): return the indexth item in the collection
                // getNodeType(): A code representing the type of the underlying object, as defined above
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {                                                             
                    // ELEMENT_NODE: The node is an Element.                    
                    Element eElement = (Element) nNode;
                    // getElementsByTagName(String name): Returns a NodeList of all descendant 
                    // Elements with a given tag name, in document order
                    // getTextContent(): This attribute returns the text content of this node and its descendants.                    
                    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 (Exception e) {
            e.printStackTrace();        
          }
    }
}
cs

- 출력값

Root element :company


Staff id : 1001
First Name : yong
Last Name : mook kim
Nick Name : mkyong
Salary : 100000
Staff id : 2001
First Name : low
Last Name : yin fong
Nick Name : fong fong
Salary : 200000


- test.xml

<?xml version="1.0" encoding="utf-8"?>
<company>
    <staff id="1001">
        <firstname>yong</firstname>
        <firstname>kong</firstname>
        <lastname>mook kim</lastname>
        <nickname>mkyong</nickname>
        <salary>100000</salary>
    </staff>
    <staff id="2001">
        <firstname>low</firstname>
        <lastname>yin fong</lastname>
        <nickname>fong fong</nickname>
        <salary>200000</salary>
    </staff>
</company>

Comments

Popular posts from this blog

[SQL] 기본 문법 정리

Oracle XE와 Oracle SQL Developer를 사용하여 공부했으며 (오라클 홈페이지에서 다운 받을 수 있다), Oracle Standard Edition에 기본적으로 존재하는 샘플 데이터 베이스인  SCOTT 계정을 사용하였다. 1. Oracle XE 설치와 기본 셋팅   - SQL*PLUS 실행 방법   처음에는 보안 상의 이유로 system 등을 제외한 계정은 막혀있을 수 있다.   따라서 system 계정으로 로그인 한다(암호는 설치 시 설정한 암호).    - cmd에서    > sqlplus / sysdba   - 사용자 목록 확인   > SELECT username, default_tablespace, account_status FROM DBA_USERS;    Expired & Locked로 표시되는 사용자는 계정을 풀기 전에는 로그인이 되지 않는다.   - 계정 Unlock   > create user scott identified by tiger;   - 계정 권한 부여   > grant connect, resource to scott;   - scott 계정으로 로그인    > conn scott   - 테이블 구조 확인   > desc emp   > desc dept   > desc bonus   > desc salgrade --------------------------------------------------------------------------...

아나콘다 파이썬에서 IDLE 실행하기

아주 간단하다. 아나콘다 설치 시 함께 설치되는데 아이콘이 생성되지 않을 뿐이다.  설치한 폴더에 가서 idle.bat을 실행 시키면 된다. 내 경우에는  C:\Anaconda\Lib\idlelib\idle. bat 를 실행 시키면 된다!

[주식] 기업 가치 측정의 기초! 유상 증자, PER 이해하기

최근에 주식을 시작했다. 단타는 이제 그만하고 본격적으로 가치투자를 하기 위해 재무재표와 투자 지표 보는 법을 공부하기 시작했다. 하나하나 공부하면서 그 내용을 블로그에 정리해 보려고 한다. 개인적으로 공부하는 내용이고 쉽게 설명하려다 보니 정확하지 않는 부분이 있을 수 있다. 우선 위키피디아의 정의는 이렇다. 주가수익률 위키백과, 우리 모두의 백과사전. 주가수익률 (Price Earnings Ratio, 간단히  PER )은  주가의 상황을 판단하는데 사용되는 지표  가운데 하나로,  주가순자산비율 (PBR)과 함께 자주 사용되는 용어이다. 미국 에서는  P/E  또는  PE 로 표시하기도 한다. 개요 [ 편집 ] 주가수익률은 주가를 1주당 순이익 (EPS)으로 나눈 값이다.  예를 들어 주가 10,000 원짜리 기업이 주당 1,000 원의 순익을 거뒀다면 PER은 10배가 된다. 주가 5,000 원짜리 기업이 주당 1,000 원의 순익을 거뒀다면 PER은 5배가 된다. 즉 두 기업은 이익은 같은데도 전자의 기업은 주가가 두배로 평가되어 있는 셈이다. [1] 투자지표 [ 편집 ] 흔히 PER이 낮으면 이익에 비해 주가가 저평가된 종목으로, 높으면 고평가된 종목으로 간주된다. 따라서  가치투자 에서는 PER이 낮은 종목을 매수하여 보유하는 방법이 자주 언급된다. 비판 [ 편집 ] 다만 이러한 방식이 높은 이익을 가져오는가에 대해서는 부정적인 의견이 많다. PER이 높은 종목의 경우, 현재의 이익보다 미래의 성장성이 좋아 주가가 높게 형성된 경우도 많기 때문이다. 특히, 성장이 빠른 업종에서 수익성보다 매출 성장이 중시되는 상황에서는 이익보다 매출이 더 중요한 기준이 되므로 PER은 유용하지 못한 지표가 된다. [1] 예를 들어 앞의 예에서 PER 10배인 기업은 PER 5배인 기업과 순이익은 같지만 매...