[java] XML 파일에서 속성 값 읽기
XML 파일에서 속성 값을 읽는 방법에 대해 다룰 것입니다.
XML 파일을 읽는 가장 일반적인 방법은 DOM(Document Object Model)을 사용하는 것입니다. DOM을 사용하여 XML 파일을 트리 구조로 표현하고, 그 안에 있는 요소와 속성 값에 접근하는 것이 가능합니다.
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class ReadXML {
public static void main(String[] args) {
try {
File xmlFile = new File("example.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("elementName");
for (int temp = 0; temp < nodeList.getLength(); temp++) {
Element element = (Element) nodeList.item(temp);
String attributeValue = element.getAttribute("attributeName");
System.out.println("Attribute value: " + attributeValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
위의 코드는 example.xml
파일에서 “elementName” 요소의 “attributeName” 속성 값을 읽어옵니다.
소스 코드의 주석과 함께 참고 자료를 통해 DOM을 사용하여 XML 파일에서 값을 읽는 방법에 대해 더 자세히 이해할 수 있습니다.
참고 자료:
이제 XML 파일에서 속성 값을 읽는 방법에 대한 기본적인 이해를 갖게 되었습니다.