从我的XML文件中获取最大ID?

时间:2014-04-08 15:01:15

标签: java xml xpath jaxb

我使用JAXB生成我的XML并使用XPATH从我的xml获取最大id,但是当我从XML获取max Id时遇到问题。例外:"提供的JAXBContext [class com.sun.xml.bind.v2.runtime.JAXBContextImpl]不是EclipseLink JAXBContext,因此无法转换。"

获取最大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>

1 个答案:

答案 0 :(得分:0)

JAXB将根据您的XML

创建一个Project类

您的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属性