XMLDecoder >> java.lang.IllegalArgumentException:不支持的元素

时间:2019-03-19 22:35:23

标签: java xml deserialization xml-deserialization illegalargumentexception

收到此错误

  

java.lang.IllegalArgumentException:不支持的元素:net

来自此示例xml文件

<?xml version="1.0" encoding="UTF-8"?>
    <net>
       <node label="A">
        ...
       </node>
       <node label="B">
        ...
       </node>
       <node label="C">
        ...
       </node>
    </net>

使用这些Java代码行

    ...
    FileInputStream file = new FileInputStream("example.xml");
    XMLDecoder decoder = new XMLDecoder(file);
    Object decodedResistors = (Object) decoder.readObject();
    file.close();
    ...

1 个答案:

答案 0 :(得分:1)

请勿将java.beans.XMLDecoder用于反序列化自定义XML有效负载。它不是为此设计的。阅读文章Long Term Persistence of JavaBeans Components: XML Schema。它包含一些示例XML负载,可以通过XMLDecoder反序列化:

<?xml version="1.0" encoding="UTF-8" ?>
<java version="1.4.0" class="java.beans.XMLDecoder">
    <void id="myController" property="owner"/>
    <object class="javax.swing.JButton">
        <void method="addActionListener">
            <object class="java.beans.EventHandler" method="create">
                <class>java.awt.event.ActionListener</class>
                <object idref="myController"/>
                <string>doIt</string>
            </object>
        </void>
    </object>
</java>

如果您需要反序列化自定义XML,请使用JAXBJackson XML。您需要创建带有POJO批注的JAXB模型:

@XmlRootElement(name = "net")
@XmlAccessorType(XmlAccessType.FIELD)
class Net {

    @XmlElement(name = "node")
    private List<Node> nodes;

    // getters, setters, toString
}

@XmlAccessorType(XmlAccessType.FIELD)
class Node {

    @XmlAttribute
    private String label;

    // getters, setters, toString
}

用法示例:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.File;
import java.util.List;

public class JaxbApp {

    public static void main(String[] args) throws Exception {
        File xmlFile = new File("./resource/test.xml").getAbsoluteFile();

        JAXBContext jaxbContext = JAXBContext.newInstance(Net.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        Object net = unmarshaller.unmarshal(xmlFile);
        System.out.println(net);
    }
}

打印:

Net{nodes=[Node{label='A'}, Node{label='B'}, Node{label='C'}]}

另请参阅: