개인 공부용으로 뉴스 페이지를 가져오기 위해 찾아보던중 DocumentBuilderFactory에 대해 공부할 기회가 생겨 정리할겸 포스팅한다.
초기 조건
RSS 뉴스 가져오기 -> JDBC의 rss 뉴스를 가져왔으며 링크는 다음과 같다.
https://news.jtbc.co.kr/Etc/RssService.aspx
데이터 확인하기 -> 해당 부분에서 경제파트를 가져오기 위하여를 확인한 결과 다음과 같은 xml이 출력되었다.
https://fs.jtbc.co.kr/RSS/economy.xml
여기서 우리가 필요한건 title, link, description, pubDate이니 이것을 저장할 VO를 만들었다.
ItemVO.java
public class ItemVO {
private String title;
private String link;
private String description;
private String pubDate;
public ItemVO(String title, String link, String description, String pubDate) {
this.title = title;
this.link = link;
this.description = description;
this.pubDate = pubDate;
}
@Override
public String toString() {
return "ItemVO [title=" + title + ", link=" + link + ", description=" + description + ", pubDate=" + pubDate
+ "]";
}
}
Controller
@RequestMapping("homepage/newsPage")
public String newsPage(Model model) throws ServletException, IOException {
System.out.println("aa2");
List<ItemVO> items = new ArrayList<>();
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new URL("https://fs.jtbc.co.kr/RSS/economy.xml").openStream());
NodeList nList = doc.getElementsByTagName("item");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String title = eElement.getElementsByTagName("title").item(0).getTextContent();
String link = eElement.getElementsByTagName("link").item(0).getTextContent();
String description = eElement.getElementsByTagName("description").item(0).getTextContent();
String pubDate = eElement.getElementsByTagName("pubDate").item(0).getTextContent();
items.add(new ItemVO(title, link, description, pubDate));
}
}
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("items", items);
return "homepage/newsPage";
}
이게 기본적인 코드를 뜻하는데 각각 어떤것을 의미하는지 확인해보곘다.
- DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); //A
- DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); //B
- Document doc = dBuilder.parse(new URL("https://fs.jtbc.co.kr/RSS/economy.xml").openStream()); //C
- NodeList nList = doc.getElementsByTagName("item"); //D
DocumentBuilderFactory (A)
public abstract class DocumentBuilderFactory
extends Object
//Defines a factory API that enables applications to obtain a parser that produces
//DOM object trees from XML documents.
번역
-
응용 프로그램이 XML 문서로부터 DOM 객체 트리를 생성하는 파서를 얻을 수 있게 하는 팩토리 API를 정의합니다.
즉, A는 XML을 우선 파싱하기 위해 인스턴스를 생성한 코드이다.링크:https://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/DocumentBuilderFactory.html
DocumentBuilder (B)
public abstract class DocumentBuilder
extends Object
//Defines the API to obtain DOM Document instances from an XML document. Using this class, an application programmer can obtain a Document from XML.
//An instance of this class can be obtained from the DocumentBuilderFactory.newDocumentBuilder() method. Once an instance of this class is obtained, XML can be parsed
//from a variety of input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources.
//Note that this class reuses several classes from the SAX API.
//This does not require that the implementor of the underlying
//DOM implementation use a SAX parser to parse XML document into a Document.
//It merely requires that the implementation communicate with the application using these existing APIs.
번역
- 이 클래스는 XML 문서에서 DOM Document 인스턴스를 얻기 위한 API를 정의합니다. 이 클래스를 사용하면, 응용 프로그램 프로그래머는 XML로부터 Document를 얻을 수 있습니다. 이 클래스의 인스턴스는 DocumentBuilderFactory.newDocumentBuilder() 메소드로부터 얻을 수 있습니다. 일단 이 클래스의 인스턴스를 얻으면, 다양한 입력 소스로부터 XML을 파싱할 수 있습니다. 이 입력 소스들은 InputStreams, Files, URLs 및 SAX InputSources입니다
Document (C)
Document doc = dBuilder.parse(new URL("https://fs.jtbc.co.kr/RSS/economy.xml").openStream());
번역
- Document 인터페이스는 전체 HTML 또는 XML 문서를 나타냅니다.
- 요소, 텍스트 노드, 주석, 처리 지시문 등은 Document의 맥락 외부에서 존재할 수 없기 때문에, Document 인터페이스는 이러한 객체들을 생성하기 위한 팩토리 메소드들도 포함하고 있습니다.
new URL("https://fs.jtbc.co.kr/RSS/economy.xml") - URL 객체를 생성
.openStream() - URL의 내용을 읽기 위한 연결
dBuilder.parse(...): DocumentBuilder 객체의 parse 메소드를 사용해, 읽어온 XML 데이터를 파싱 -> 이 과정에서 XML 문서의 구조를 분석하고, 해당 구조에 따라 DOM 객체 트리를 생성
Document doc = ...: 파싱의 결과로 생성된 DOM 객체 트리의 루트인 Document 객체를 doc 변수에 할당
즉,1. 사용하려는 요소(HTML, XML 요소들)를 담기위한 Document를 선언하였고2. URL을 하드코딩하여 값을 가져왔고 3. 파싱한뒤 doc에 할당하였다.링크 : https://docs.oracle.com/javase/8/docs/api/org/w3c/dom/Document.html
NodeList (D)
NodeList nList = doc.getElementsByTagName("item");
public interface NodeList
The NodeList interface provides the abstraction of an ordered collection of nodes
without defining or constraining how this collection is implemented.
NodeList objects in the DOM are live.
The items in the NodeList are accessible via an integral index, starting from 0.
번역
- NodeList 인터페이스는 노드들의 순서가 있는 컬렉션을 추상화합니다.
- DOM 내의 NodeList 객체들은 실시간으로 반응합니다.
- NodeList 내의 항목들은 0부터 시작하는 정수 인덱스를 통해 접근할 수 있습니다.
- 이 컬렉션이 어떻게 구현되는지 정의하거나 제약하지는 않습니다.
doc.getElementsByTagName("item") - Document 객체인 doc에 대해 getElementsByTagName 메서드를 호출
- 주어진 태그 이름("item")과 일치하는 모든 요소를 문서 전체에서 찾습니다.
- "item" 태그는 RSS 피드에서 개별 뉴스 항목을 나타내는 데 사용되므로, 이 호출은 RSS 피드 내의 모든 뉴스 항목을 나타내는 요소들의 목록을 반환합니다.(getElementsByTagName 메서드는 NodeList 객체를 반환)
NodeList nList - 메서드로부터 반환된 NodeList 객체를 nList 변수에 할당합니다. 이 변수를 통해 개발자는 찾아낸 모든 "item" 요소들에 접근할 수 있게 됩니다. 각 "item" 요소는 개별 뉴스 항목의 데이터를 포함하고 있으므로, nList를 순회하면서 필요한 정보(예: 뉴스 제목, 링크, 설명 등)를 추출할 수 있습니다.
링크 : https://docs.oracle.com/javase/8/docs/api/org/w3c/dom/NodeList.html
요약
A - DocumentBuilderFactory.newInstance();
- XML 입력을 DOM 객체 트리로 생성할 수 있는 파서의 인스턴스를 얻기 위한 설정.
B - DocumentBuilder();
- XML 데이터를 읽고 이를 해석하여 DOM Document 인스턴스로 변환하는 역할
C - Document
- Document 인터페이스는 전체 HTML 또는 XML 문서를 의미
D - NodeList
- Document에서 얻을 값을 NodeList 형태로 저장
'JAVA' 카테고리의 다른 글
자바 주니어 질문 100건 (기초) (0) | 2024.11.02 |
---|---|
Call by value와 Call by reference (0) | 2024.02.24 |
스레드풀 (0) | 2023.03.07 |
프로세스와 스레드 (0) | 2023.03.07 |
동일성(identity)과 동등성(equality) (0) | 2023.02.26 |