在Java(Apache Camel)中将XML解析为对象

3
我有一个非常简单的程序,可以从互联网上获取今天汇率的XML文件。我想将这个XML文件的内容转换为Java对象,以便稍后使用它。
我尝试转换的XML文件在这里:https://www.dnb.no/portalfront/datafiles/miscellaneous/csv/kursliste_ws.xml 当我运行程序时,我会收到以下错误消息:
mvn clean compile camel:run Caused by: org.apache.camel.RuntimeCamelException: org.apache.camel.FailedToCreateRouteException: Failed to create route route2: Route(route2)[[From[direct:readFile]] -> [Log[### Read file ... because of Provider com.sun.xml.bind.v2.ContextFactory could not be instantiated: javax.xml.bind.JAXBException: "com.domain.subdomain.domain" doesnt contain ObjectFactory.class or jaxb.index Caused by: javax.xml.bind.JAXBException: "com.domain.subdomain.domain" doesnt contain ObjectFactory.class or jaxb.index
以下是我的Java文件。 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.domain.subdomain</groupId>
    <artifactId>xml-to-object</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.apache.camel/camel-core -->
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>2.20.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.camel/camel-spring -->
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring</artifactId>
            <version>2.20.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>spi-annotations</artifactId>
            <version>2.20.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.camel/camel-jms -->
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jms</artifactId>
            <version>2.20.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-http4</artifactId>
            <version>2.20.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-quartz</artifactId>
            <version>2.20.0</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.apache.activemq/activemq-all -->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.15.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.camel/camel-jaxb -->
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jaxb</artifactId>
            <version>2.20.2</version>
        </dependency>


    </dependencies>


    <build>
        <plugins>
            <!-- Allows the routes to be run via 'mvn camel:run' -->
            <plugin>
                <groupId>org.apache.camel</groupId>
                <artifactId>camel-maven-plugin</artifactId>
                <version>2.20.0</version>
            </plugin>
        </plugins>
    </build>
</project>

resources/META-INF/spring/camel-contxt.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://camel.apache.org/schema/spring
       http://camel.apache.org/schema/spring/camel-spring.xsd">

    <bean id="CurrencyRoute" class="com.domain.subdomain.routes.CurrencyRoute">
        <property name="currencyWsURL" value="www.dnb.no/portalfront/datafiles/miscellaneous/csv/kursliste_ws.xml" />
    </bean>

    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <routeBuilder ref="CurrencyRoute"/>
    </camelContext>

</beans>

java/com/domain/subdomain/CurrencyRoute.java:

package com.domain.subdomain.routes;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.converter.jaxb.JaxbDataFormat;
import org.apache.camel.spi.DataFormat;


public class CurrencyRoute extends RouteBuilder {


    private String currencyWsURL;

    @Override
    public void configure() {
        DataFormat jaxbDataFormat = new JaxbDataFormat("com.domain.subdomain.domain");


        from("quartz://myTimer?trigger.repeatCount=0")
                .log("### Quartz trigger ###")
                .to("direct:readFile");

        from("direct:readFile")
                .log("### Read file ###")
                .to("https4://" + currencyWsURL)
                .unmarshal(jaxbDataFormat)
                .log("${body}");
    }

    public void setCurrencyWsURL(String currencyWsURL) {
        this.currencyWsURL = currencyWsURL;
    }
}

java/com/domain/subdomain/domain/Currency.java:

package com.domain.subdomain.domain;

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

@XmlRootElement(name = "valuta")
@XmlAccessorType(XmlAccessType.FIELD)
public class Currency {

    @XmlElement(name = "land")
    String country;

    @XmlElement(name = "isokode")
    String isoCode;

    @XmlElement(name = "kode")
    String code;

    @XmlElement(name = "enhet")
    Double unit;

    @XmlElement(name = "navn")
    String name;

    @XmlElement(name = "kjop")
    Double transferPurcase;

    @XmlElement(name = "salg")
    Double transferSell;

    @XmlElement(name = "endring")
    Double transferChanges;

    @XmlElement(name = "forrige")
    Double transferPrevious;

    @XmlElement(name = "midtkurs")
    Double transferMiddleCourse;

    @XmlElement(name = "kjop")
    Double notePurcase;

    @XmlElement(name = "salg")
    Double noteSell;



    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getIsoCode() {
        return isoCode;
    }

    public void setIsoCode(String isoCode) {
        this.isoCode = isoCode;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Double getUnit() {
        return unit;
    }

    public void setUnit(Double unit) {
        this.unit = unit;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getTransferPurcase() {
        return transferPurcase;
    }

    public void setTransferPurcase(Double transferPurcase) {
        this.transferPurcase = transferPurcase;
    }

    public Double getTransferSell() {
        return transferSell;
    }

    public void setTransferSell(Double transferSell) {
        this.transferSell = transferSell;
    }

    public Double getTransferChanges() {
        return transferChanges;
    }

    public void setTransferChanges(Double transferChanges) {
        this.transferChanges = transferChanges;
    }

    public Double getTransferPrevious() {
        return transferPrevious;
    }

    public void setTransferPrevious(Double transferPrevious) {
        this.transferPrevious = transferPrevious;
    }

    public Double getTransferMiddleCourse() {
        return transferMiddleCourse;
    }

    public void setTransferMiddleCourse(Double transferMiddleCourse) {
        this.transferMiddleCourse = transferMiddleCourse;
    }

    public Double getNotePurcase() {
        return notePurcase;
    }

    public void setNotePurcase(Double notePurcase) {
        this.notePurcase = notePurcase;
    }

    public Double getNoteSell() {
        return noteSell;
    }

    public void setNoteSell(Double noteSell) {
        this.noteSell = noteSell;
    }
}

你的 jaxb 包(com.domain.subdomain.domain)是否包含了预期的 ObjectFactory 类?如果是你自己创建绑定,那可能不是这样的情况。 - Benoit
你使用的是哪个Java版本? - mtj
我不确定什么是ObjectFactory类。我需要创建它吗? 我正在使用Java 8。 - Europa
2个回答

1
尝试根据异常设置上下文...参考下面的代码。
@Override 
            public void configure() throws Exception { 

                JaxbDataFormat jaxbDataFormat = new JaxbDataFormat(); 
        // add path to class - 
                jaxbDataFormat.setContext(JAXBContext.newInstance(com.domain.subdomain.domain.Currency.class));
                 from("quartz://myTimer?trigger.repeatCount=0")
        ....
        ....

1
这个给我报错了:无法解析方法 'setContext' javax.xml.bind.JAXBContext - Europa
查看JAXBContext.newInstance的规范(...这里应该放什么...)。我的代码供参考,如果您提供正确的输入,它应该能正常工作。 - Sheetal Mohan Sharma

1

这可能与您实现路由的方式有关。以下示例对我来说可以正常工作:

private static final String INBOX = "file:data/inbox?noop=true&include=.*.xml";

@Override
public void configure() throws Exception {

    JAXBContext context = JAXBContext.newInstance(new Class[]{io.tiago.feed.Animals.class});
    JaxbDataFormat xmlDataFormat = new JaxbDataFormat();
    xmlDataFormat.setContext(context);

    from(INBOX).doTry().unmarshal(xmlDataFormat)
            .split().tokenizeXML("status")
            // IF YOUR PAYLOAD IS BIG, YOU MAY WANT TO SPLIT IT IN STREAMING MODE WHICH MEANS IT WILL SPLIT THE INPUT MESSAGE IN CHUNKS
            .streaming()
            .to("file://data/outbox")
            .end();
}

你也可以查看我的存档https://metiago.github.io/dev/2017/02/12/java-apache-camel-xml.html?query=camel以获取更好的示例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接