我是 JAXB 的新手,我正在尝试使用 JAXB 进行采样。
尝试显示 MenuList.xml 中的值
----菜单列表.xml------------
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<menulist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Category1 name="Development">
<MenuItem1>Projects</MenuItem1>
<MenuItem2>Library</MenuItem2>
<MenuItem3>Library1</MenuItem3>
</Category1>
</menulist>
----------------------------MenuList.xsd---------------- ---
<?xml version="1.0" encoding="utf-8" ?>
<!--Created with Liquid XML Studio Developer Edition (Trial) 8.0.11.2171 (http://www.liquid-technologies.com)-->
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="menulist">
<xs:complexType>
<xs:sequence>
<xs:element name="Category1">
<xs:complexType>
<xs:attribute name="MenuItem1" type="xs:string" use="required" />
<xs:attribute name="MenuItem2" type="xs:string" use="required" />
<xs:attribute name="MenuItem3" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
我运行 xsd 文件的 uisng 命令生成了类。 MenuList 和对象工厂。
AppTest.java
package com.xx.menu;
import java.io.File;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.UnmarshalException;
import javax.xml.bind.Unmarshaller;
public class TestNew {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JAXBContext jc = JAXBContext.newInstance("com.xx.menu"); //Create unmarshaller
Unmarshaller um = jc.createUnmarshaller();
File file = new File ("C:\\sample\\menulist.xml");
JAXBElement element = (JAXBElement)um.unmarshal(file);
Menulist menulist= (Menulist) element.getValue ();
System.out.println("name : "+menulist.getMenu());
}
catch( UnmarshalException ue ) {
ue.printStackTrace();
System.out.println( "Caught UnmarshalException" );
} catch( JAXBException je ) {
je.printStackTrace();
} catch( Exception ioe ) {
ioe.printStackTrace();
}
}
}
错误:
java.lang.ClassCastException: com.xx.menu.Menulist
at com.xx.menu.TestNew.main(TestNew.java:26)
你能帮我看看我哪里出错了吗……我将非常感谢你。
谢谢
最佳答案
你把事情搞得太复杂了。如果 Unmarshaller
直接为您提供 Menulist
对象,则您无需处理 JAXBElement
。 ClassCastExcepotion
几乎可以告诉您需要做什么:
Menulist menulist= (Menulist) um.unmarshal(file);
JAXBElement
仅在某些特定情况下使用,这不是其中之一。
关于java - JAXB :Class cast exception while trying to unmarshall XML using JAXB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2763218/