gpt4 book ai didi

java - XMLDecoder >> java.lang.IllegalArgumentException : Unsupported element

转载 作者:行者123 更新时间:2023-11-30 05:43:31 26 4
gpt4 key购买 nike

出现此错误

java.lang.IllegalArgumentException: Unsupported element: 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();
...

最佳答案

不要使用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。您需要创建一个带有 JAXB 注释的 POJO 模型:

@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'}]}

另请参阅:

关于java - XMLDecoder >> java.lang.IllegalArgumentException : Unsupported element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55250966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com