티스토리 뷰

프로그래밍/java

XML을 JSON처럼 사용하기

박스여우 2016. 12. 16. 08:50

안녕하세요 박스여우입니다. 이번 포스팅은 간단하게 Java에서 XML을 JSON 처럼 사용하는 방법에 대해 알아보도록 하겠습니다.


■ Main

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.IOException;
import java.util.Properties;
 
public class XmlMain {
    
    public static void main(String args[]){
        StringOutputStream out = new StringOutputStream();
        Properties props = new Properties();
        props.setProperty("email.support""donot-spam-me@nospam.com");
        try {
            props.storeToXML(out"Support Email","UTF-8");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        System.out.println(out.getString());
    }
 
}
 
cs

XML Object 작성(Key,Value)은 Properties를 통해 진행합니다. 하지만 String 형으로 최종 결과물을 얻기 위해서는 OutputStream을 사용해야 하는데요, 저희의 목적은 파일이 아니니 StringOutputStream이라는 별도의 클래스를 만들어 해결하도록 하겠습니다.



■ StringOutputStream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.io.IOException;
import java.io.OutputStream;
 
public class StringOutputStream extends OutputStream {
    private StringBuilder mBuf;
    
    public StringOutputStream(){
        mBuf = new StringBuilder();
    }
 
    @Override
    public void write(int arg0) throws IOException {
        mBuf.append((char) arg0);
    }
 
    public String getString() {
        return mBuf.toString();
    }
 
}
 
cs

OutputStream을 가장한 StringBuffer입니다!



■ 탐색

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
File fXmlFile = new File(path);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
try {
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();
catch (ParserConfigurationException | SAXException | IOException e) {
    e.printStackTrace();
}
System.out.println(node.getNodeName());
 
NodeList list = node.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
    System.out.println(list.item(i).getNodeName());
}
cs


해당 포스팅은 단순 정리의 목적으로 작성되었습니다. 좀더 자세한 내용이나 라이브러리를 원하신다면 https://github.com/rlatjdfo112/XMLObject 요기를 참고해 주세요!

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함