使用JDOM进行XML解析(节点和属性值)

时间:2014-01-28 11:38:46

标签: xml parsing jdom

这是示例XML,假设我想提取数据“DEF”。任何想法如何通过组合节点和属性值提取,即节点应该是“容器”,属性值应该是“2”?我是JDOM和XML解析的新手。请提出你的建议。

<?xml version="1.0"?>
<Product>
    <Property>
        <Container value="1">ABC</Container>
        <Container value="2">DEF</Container>
        <Container value="3">GHI</Container>
    </Property>
</Product>

1 个答案:

答案 0 :(得分:1)

像这样

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());
        }
    }
}