来自复杂XML的Java对象,仅对Child元素感兴趣

时间:2018-12-22 12:39:12

标签: java xml spring-boot jaxb

这是我的XML文件:

<Root>
    <Id>1</Id>
    <Title>My title</Title>
    <More>
        <Extension>Ex</Extension>
        <Extra>Extra info</Extra>
            <Comments>
                <Comment date="2018-11-26T06:00:00+02:00">Hey, this is my comment</Comment>
                <Comment date="2017-11-26T06:00:00+02:00">Hey, this is my comment</Comment>
                <Comment date="2016-11-26T06:00:00+02:00">Hey, this is my comment</Comment>
                <Comment date="2011-11-26T06:00:00+02:00">Hey, this is my comment</Comment>
            </Comments>
    </More>
</Root>

我只对<Comment>数据感兴趣。 我当前的方法是使用JaxB解组,并具有Root.java,More.java,Comments.java类,其中包含类Comment.java。所以有点混乱。

我这样做没问题,但是我想知道是否有任何方法可以让您直接获取<Comment>数据,并且只有1类Comment.java?

1 个答案:

答案 0 :(得分:0)

如果您只想从XML文件中获取所有 comment 标记,则可以尝试以下方法,

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ReadComments {

    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { 
        File xml = new File("D:/data.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(xml);
        doc.getDocumentElement().normalize();
        NodeList nodeList = doc.getElementsByTagName("Comment");

        for (int i= 0; i< nodeList.getLength(); i++) {
            Node node = nodeList.item(i);

            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                System.out.printf("Comment : %s | Date : %s\n", node.getTextContent(), element.getAttribute("date"));
            }
        }
    }
}

输出:

Comment : Hey, this is my comment | Date : 2018-11-26T06:00:00+02:00
Comment : Hey, this is my comment | Date : 2017-11-26T06:00:00+02:00
Comment : Hey, this is my comment | Date : 2016-11-26T06:00:00+02:00
Comment : Hey, this is my comment | Date : 2011-11-26T06:00:00+02:00

请注意,这只是一个示例,用于解释有关获取特定标签的详细信息,您将必须根据需要修改此代码。