문제

Here is the example XML and let's say I want to extract the data "DEF". Any idea how to extract by combining node and attribute value i.e. Node should be "Container" and attribute value should be "2" ? I am new to JDOM and XML parsing. Please give your suggestions.

<?xml version="1.0"?>
<Product>
    <Property>
        <Container value="1">ABC</Container>
        <Container value="2">DEF</Container>
        <Container value="3">GHI</Container>
    </Property>
</Product>
도움이 되었습니까?

해결책

like this

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.xml.sax.Attributes;

public class ReadXMLFile {
    public static void main(String[] args) {

        SAXBuilder builder = new SAXBuilder();
        File xmlFile = new File("src/jdom.xml");

        try {

            Document document = (Document) builder.build(xmlFile);
            Element rootNode = document.getRootElement();
            Element element = rootNode.getChild("Property");
            List list = element.getChildren("Container");

            for (int i = 0; i < list.size(); i++) {

                Element node = (Element) list.get(i);

                Attribute value = node.getAttribute("value");
                if ((value.getValue().equals("2"))) {
                    System.out.println(value.getValue());

                    System.out.println("values : " + node.getText());
                }

            }

        } catch (IOException io) {
            System.out.println(io.getMessage());
        } catch (JDOMException jdomex) {
            System.out.println(jdomex.getMessage());
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top