简体   繁体   English

Java 解析XML并映射到object

[英]Java Parsing XML and mapping to object

I have an XML file that i need to map with a POJO.我有一个 XML 文件,我需要 map 和 POJO。 My XML looks like this:我的 XML 看起来像这样:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <contentType>Document</contentType>
    <siteName>mySite</siteName>
    <listName>myLib</listName>
    <folderName>docset-folder</folderName>
    <documentSetName>documentSet</documentSetName>
    <fields>
        <field name="META_1">123456789</field>
        <field name="META_2">Someone</field>
        <field name="META_3">Germany</field>
    </fields>
</data>

My POJO looks like this:我的 POJO 看起来像这样:

public class MetaData implements Serializable {
    private String contentType;   
    private String siteName;
    private String listName;
    private String folderName;
    private String documentSetName;
    private Map<String, Object> fields;
}

My objective is to be able to map any XML with any POJO, for this I found how to list the members of a class. At this stage I have a method that allow to iterate a nodelist.我的目标是能够使用任何 POJO map 任何 XML,为此我找到了如何列出 class 的成员。在这个阶段我有一个允许迭代节点列表的方法。

public static Iterable<Node> iterable(final NodeList nodeList) {
    return () -> new Iterator<Node>() {

        private int index = 0;

        @Override
        public boolean hasNext() {
            return index < nodeList.getLength();
        }

        @Override
        public Node next() {
            if (!hasNext())
                throw new NoSuchElementException();
            return nodeList.item(index++);
        }
    };
}

And a main method where I try to use DocumentBuilderFactory:以及我尝试使用 DocumentBuilderFactory 的主要方法:

public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
    String path = "src/test/resources/bill.xml";
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    // list the members of the metadata class
    List<Field> fields = Arrays.asList(MetaData.class.getDeclaredFields());


    try {
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new File(path));

        doc.getDocumentElement().normalize();

        System.out.println("Root Element :" + doc.getDocumentElement().getNodeName());
        System.out.println("------");
        NodeList list = doc.getElementsByTagName("data");
        iterable(list).forEach(node -> {
            if (node.getNodeType() == Node.ELEMENT_NODE) {

                Element element = (Element) node;

                fields.forEach(field -> {
                    if(element.getAttribute(field.getName()).length() > 0) {
                        System.out.println(element.getAttribute(field.getName()));
                    } else {
                        System.out.print(element.getElementsByTagName(field.getName()).item(0).getNodeName());
                        System.out.println(" - " + element.getElementsByTagName(field.getName()).item(0).getTextContent());
                    }
                });
            }
            // System.out.println(node.getTextContent());
        });
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }

}

I'm here just testing to get the XML properties, attributes and values.我在这里只是测试获取 XML 属性、属性和值。 This code gives me the following result:此代码给了我以下结果:

contentType - Document
siteName - mySite
listName - myLib
folderName - docset-folder
documentSetName - documentSet
fields - 
     123456789
     Someone
     Germany

My issue is that: i would expect the following:我的问题是:我期望以下内容:

contentType - Document
siteName - mySite
listName - myLib
folderName - docset-folder
documentSetName - documentSet
fields - 
META_1 - 123456789
META_2 - Someone
META_3 - Germany

My objective would be to be able to map it with a MetaData object. fields here should be added to a map with META_1 as key and 123456789 as value.我的目标是能够使用元数据 object 对其进行 map。此处的字段应添加到 map,其中 META_1 作为键,123456789 作为值。 I'm a little bit stuck here.我有点被困在这里。

In my case I parse XML files with XPath, you can get attribute names and values as seen in this thread: XPath getting attribute在我的例子中,我用 XPath 解析了 XML 个文件,你可以得到属性名称和值,如这个线程所示: XPath getting attribute

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM