[java] XML 파일에서 특정 요소의 형제 요소 모두 가져오기

Java에서 XML 파일을 다룰 때, 특정 요소의 형제 요소들을 가져와야 하는 경우가 있습니다. 이때 다음과 같이 Java의 XPath를 사용하여 원하는 요소들을 가져올 수 있습니다.

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.xpath.*;

public class XmlProcessor {
    public static NodeList getSiblingElements(String xml, String elementName) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xml);

        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        XPathExpression expr = xpath.compile("//" + elementName + "/following-sibling::*");

        return (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    }
}

위의 코드는 주어진 XML 문자열과 특정 요소의 이름을 받아 해당 요소의 형제 요소들을 가져오는 메서드를 보여줍니다. 이 메서드는 XPath를 사용하여 주어진 XML에서 특정 요소의 형제 요소들을 선택합니다.

이제 위의 메서드를 사용하여 XML 파일에서 특정 요소의 형제 요소들을 간단하게 가져올 수 있습니다.

참고 문헌:

  1. Oracle, “The Java Tutorials - XPath Tutorial”: https://docs.oracle.com/javase/tutorial/jaxp/xslt/xpath.html
  2. W3C, “XPath Version 1.0”: https://www.w3.org/TR/xpath/
  3. TutorialsPoint, “Java XML - Parsing XML using XPath in Java”: https://www.tutorialspoint.com/java_xml/java_xpath_parse_document.htm