2014-04-08 16 views
0

我使用JAXB生成我的XML,並使用XPATH從我的XML中獲取最大ID,但是當我從我的XML中獲取最大ID時遇到問題。例外:「提供的JAXBContext [class com.sun.xml.bind.v2.runtime.JAXBContextImpl]不是EclipseLink JAXBContext,因此無法轉換。」從我的XML文件中獲取最大ID?

這種方法獲得最大的編號:

public int GetMaxID() throws JAXBException { 
     try { 
     JAXBContext jc = JAXBContext.newInstance(Project.class); 
     XMLContext xmlContext = JAXBHelper.unwrap(jc, XMLContext.class);///**here is Exception** 
     Project project = new Project(); 
     int maxId =xmlContext.getValueByXPath(project,"Project[not(Project/Layer/@idLayer>@idLayer)]",   null, int.class); 
      }catch (Exception e) { 
     e.printStackTrace(); 
      } 
     return -1; 
    } 

我的XML:

<Project name="p1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > 
    <Layer idLayer="0"> 
    <LayerName>LayerName</LayerName> 
    </Layer> 
    <Layer idLayer="1"> 
    <LayerName>LayerName</LayerName> 
    </Layer> 
    <Layer idLayer="2"> 
    <LayerName>LayerName</LayerName> 
    </Layer> 
    <Layer idLayer="3">//**I want get this Id** 
    <LayerName>LayerName</LayerName> 
    </Layer> 
</Project> 

回答

0

JAXB將創建一個基於您的XML項目類

你JAXB方法是有點過。 ..您的Project類也必須匹配XML內容

JAXBContext jc = JAXBContext.newInstance(Project.class); 
Unmarshaller unmarshaller = jc.createUnmarshaller(); 
Project xmlData = (Project) unmarshaller.unmarshall(---XML CONTENT---); 

然後你做

xmlData.getLayer().get(xmlData.size()-1).getId(); 

看看這個鏈接http://www.mkyong.com/java/jaxb-hello-world-example/

*編輯你可能會得到這樣做,因爲Project不符合您的XML(錯誤,即沒有LayerLayerName財產

+0

感謝您的回答,但您並未在代碼中使用Xpath,請告訴我如何在我的代碼中使用xpath以獲取最大ID。 – MohammadTofi

+0

其JAXB或Xpath我不明白爲什麼你會使用兩個。也許你應該對Xpath進行一些研究http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/ –

+0

非常感謝你回答我 – MohammadTofi