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

ftp, sftp, ssh 차이점

telnet ==> ssh  ftp ==> sftp  p2p방식이라 보안에 취약한것이 아니라 telnet과 ftp 인 경우는 패킷을 캡쳐해서 보면, 평문이기 때문에 보여져서는 안될부분(패스워드, 계정 등)이 쉽게 노출된다. 이는 아주 큰 문제를 발생시킬 수 있다. 이런 취약점을 보안하기 위해서 telnet은 ssh로  f tp는 sftp로 암호화된 프로토콜 SSL을 사용하는게 좋다. 이렇게 하면 모든 패킷을 암호화 해서 주고 받으므로  패킷을 잡아내더라도 해독하는데 슈퍼컴퓨터로 1달 이상 걸리게 된다.  cf)  telnet 과 ftp의 차이 telnet: 쉘권한을 취득(ex. bash)하여 마치 로컬 컴퓨터를 다루는 것처럼  실행되는 접속 방법  ftp: 파일을 전송하기 위한 프로토콜.  telnet으로 파일 전송을 못하며(zmodem프로토콜을 사용하면 되지만, 엄청 느림) ftp로 시스템을 관리하거나 데몬을 띄우는 것은 불가능.  Reference https://wpengine.com/resources/how-to-access-wordpress-files-using-sftp/ https://www.linux.co.kr/home2/board/subbs/board.php?bo_table=linuxserver&wr_id=19987

Anaconda tensorflow-gpu 설치 에러 [WinError 126] 지정된 모듈을 찾을 수 없습니다, importError: Could not find 'cudnn64_6.dll'

anaconda를 이용하여 tensorflow cpu 버전을 사용하다가 training이 끝나지를 않아서  gpu 버전을 써보기로 했다. cpu 버전은 나름 쉽게 설치했었는데 gpu는 조금 더 까다로웠다. 블로그들을 참고해보니 막 무슨 파일을 다운 받고 어디에 붙여넣고 하라는데  처음에는 이해가 잘 안됐다. 내가 이해한대로 해보자면, 우선 다른 블로그를 참고해서 아나콘다와 tensorflow cpu 버전 설치 직전까지 진행해주시고, 필요한 파일은  CUDA 8.0 CuDNN 6.0 두 파일을 순서대로 설치. 대충 내용을 보니 CUDA 8.0은 그냥 설치하는 파일이고 CuDNN는 설치한 cuda 폴더 안에 추가하는 라이브러리, 기타등등 파일인데 다른 블로그에서는 CuDNN 폴더를 다 붙여 넣으라고도 했지만 딱 봐도 확연히 안에 들어있는 파일이 달라서 CuDNN 폴더에 있는 파일을 기존 cuda 폴더 안에 붙여 넣어주었다. 아무튼 여기서 주의해야 될 점은 CuDNN이 6.0이라는 것이다. 다른 블로그에서는 5.1을 받으라고 되어있는데 이상하게 내 anaconda에서는 계속 cudnn64_6.dll 파일을 찾을 수 없다고 에러가 떴다. 바로 이 에러이다. 알아보니 5.1은 bin 폴더안에 cudnn64_5.dll를 가지고 있고 6.0이 cudnn64_6.dll을 갖고 있었다. cudnn64_6.dll을 기본 설치 폴더 기준 C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\bin 안에 붙여넣으니 성공적으로 tensorflow-gpu를 이용할 수 있게 되었다.

우분투 18.04 react-native run-android 실행 시 javax.net.ssl.SSLException 에러

리엑트 네이티브를 시작했다. ( 참고 ) 기본 튜토리얼 에서  create-react-native-app 를 사용하는 예제는 쉽게 실행됐는데 바로 요놈! react-native-cli 를 써서  react- native init [프로젝트 이름]  로 실행하는 예제는 뭐가 문제인지 실행한번 하는데 엄청나게 애를 먹였다. 우선 리액트 공식 홈페이지에서 하라는데로 다 했다는 전제하에 참고하시면 된다. 나름 다 잘 따라했다고 생각했는데 문제는 자바(jdk)였다. JAVA_HOME 환경변수 설정이 안되어 있었다. 일단 초기에 echo $JAVA_HOME 이라고 쳤는데 아무 것도 안뜨면 환경변수 설정이 아예 안돼있는 것이다. 순서 대로 체크리스트를 만들어보자면, 1. jdk버전을 확인하자 Java Development Kit React Native requires a recent version of the Java SE Development Kit (JDK).  Download and install JDK 8 or newer  if needed. cd /usr/lib/jvm/ 를 하면 현재 설치된 jdk들을 확인 할 수 있다. jdk8 이상의 버전이 없다면 아래 명령어로 다운 받자 sudo add-apt-repository ppa:webupd8team/java sudo apt-get update sudo apt-get install oracle-java8-installer 2. JAVA_HOME 환경 변수를 등록하기 위해 cd ~ 를 하여 홈으로 이동하고 숨김 파일인 .bashrc를 수정하자. 튜토리얼에는  $HOME/.bash_profile 이라고 되어 있지만 18.04에서는 저 파일이 없어서 알아보니 bashrc를 수정하면 된다. 나는 vim을 쓰므로 vim .bashrc 라고 입력했다. nano나 다른 편집...