不使用Xstream,也不实用Jaxb,自动生成实体类;
step1:生成xsd文件
首先需要一个jar包:
trang.jar包下载地址:http://www.java2s.com/Code/Jar/t/Downloadtrang20091111jar.htm
将要解析的xml文件与 trang.jar 放在同级目录下,然后在此目录执行以下指令
//执行成功后会在当前目录下生成对应的xsd文件
//test.xml文件是你的xml文件名,test.xsd是你要生成的xsd文件名
java -jar trang.jar test.xml test.xsd
step2:生成model
这个有两种方式:
方式一:
根据xsd生成Bean
执行完上述命令后会在当前文件生成test.xsd,然后执行如下命令;
xjc -p workspace.test test.xsd -d e:
-p:workspace.test是包名
-d:要生成到哪的文件目录
执行完上述命令后会在E:workspace\test目录下生成实体类;
以上都是我借鉴的一位大哥的博客内容,生成xsd文件亲测有效,但是生成实体类我没试成功。
这是上面内容的原文链接:
java使用jaxb解析XML(含根据xml自动生成实体类)
方式一我使用失败了,同样失败的同学可以参考一下我使用成功的方式二
方式二:
使用eclipse
创建一个EMF项目
项目名
选中xsd文件
选中要生成的schema
生成Model Code
在src目录下就会生成实体类了
运行代码:
import Test.util.TestResourceFactoryImpl;//生成的实体类
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.omg.schema.spec.xmi._2.DocumentRoot; //生成的实体类
public static DocumentRoot xmlRead(String path) {
try {
ResourceSet rs = new ResourceSetImpl();
rs.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xml", new TestResourceFactoryImpl());
URI uri = URI.createURI("file:/" + path);
Resource resource = rs.getResource(uri, true);
DocumentRoot documentRoot = (DocumentRoot)resource.getContents().get(0);
return documentRoot;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
TestResourceFactoryImpl的对应位置:
TestResourceFactoryImpl(Test前缀是根据你的项目名生成的)
运行结果: