不使用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項目
創建emf項目.png
項目名
項目名.png
選中xsd文件
選中xsd.png
選中要生成的schema
選中要生成的schema.png
生成Model Code
生成了schema.png
生成model.png
在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前綴是根據你的項目名生成的)
TestResourceFactoryImpl.png
運行結果:
企業微信截圖_16385256292671.png