2016-08-27 105 views
0

我想使用jaxb解析xml字符串。實際上,我需要提取文字中的十進制值。使用jaxb解析xml字符串

這就是XML字符串:

<results> 
    <result> 
     <binding name="value"> 
     <literal datatype="http://www.w3.org/2001/XMLSchema#decimal">369.0</literal> 
     </binding> 
    </result> 
    </results> 

我有一個Java類結果:

package client; 

import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlRootElement; 

@XmlRootElement 
public class Results { 

    @XmlElement 
    String result; 

    @XmlElement 
    Double binding; 

    @XmlElement 
    Double literal; 
    public Double getLiteral() 
    { 
     return literal; 
    } 
    public Double geBinding() 
    { 
     return binding; 
    } 
    public String getResult() 
    { 
     return result; 
    } 

} 

當我試圖打印的價值,我越來越空。所以我如何獲得文字標籤之間的十進制值?

Results re=(Results) JAXBContext.newInstance(Results.class) 
      .createUnmarshaller() 
      .unmarshal(new StringReader(my_xml)); 

System.out.println(re.getLiteral()); 

回答

1

您的結果類不反映您嘗試解析的XML的結構。 results元素由result元素組成,該元素又由binding組成,並且由literal組成。我們將不得不遵循類似的結構。

@XmlRootElement 
public class Results { 

    @XmlElement 
    Result result; 

    public Result getResult() { 
     return result; 
    } 
} 

public class Result { 
    @XmlElement 
    Binding binding; 

    public Binding getBinding() { 
     return binding; 
    } 
} 

public class Binding { 
    @XmlElement 
    Double literal; 

    public Double getLiteral() { 
     return literal; 
    } 
} 

要訪問的literal值,我們可以調用的getter像results.getResult().getBinding().getLiteral()

但是,如果這是一次性發生,並且您的應用程序不會處理XML很多,則可以考慮使用XPath

0

一個簡化代碼的方法是使用​​的EclipseLink's JAXB及其XmlPath註釋允許提供一種XPATH使得可以直接映射的元素或屬性內容到您的字段,其允許避免具有用於每個子元件的額外類。

例如,在你的情況,映射將是:

@XmlPath("result/binding/literal/text()") 
Double literal; 

您需要這個依賴添加到您的項目:

<dependency> 
    <groupId>org.eclipse.persistence</groupId> 
    <artifactId>eclipselink</artifactId> 
    <version>2.6.3</version> 
</dependency> 

,並明確指定上下文工廠使用的感謝在您的啓動命令中設置的系統屬性-Djavax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

這裏有一篇關於MOXy的好文章,它描述瞭如何簡化您的代碼與其功能。