【问题标题】:MOXy @XmlPath annotation can't read same XPaths more than onceMOXy @XmlPath 注释不能多次读取相同的 XPath
【发布时间】:2018-01-21 22:26:04
【问题描述】:

我一直在努力使下面的程序工作,但我的代码或@XmlPath 注释似乎存在一些严重的缺陷。 我正在尝试解析的 XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<information>
    <customer id="customer1">
        <billingAddress id="address1">
            <street id="street1">1 Billing Street</street>
            <street id="street2">2 Billing Street</street>
        </billingAddress>
    </customer>
</information>

我正在创建的 Pojo:

package parser;


import lombok.ToString;
import org.eclipse.persistence.oxm.annotations.XmlPath;

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

@ToString
@XmlRootElement(name = "information")
@XmlAccessorType(XmlAccessType.FIELD)
public class Information {

    @XmlPath("customer/@id")//-------------------------------------> (1)
    private String customerId;

    @XmlPath("customer[@id='customer1']/billingAddress/@id") //-----> (2)
    private String billingAddressId;                          

}

我如何解组 xml:

import parser.Information;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;

public class Main {
    public static void main(String[] args) throws JAXBException {
        JAXBContext jaxbContext =  org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(new Class[]{Information.class}, null);
        Unmarshaller jaxbMarshaller = jaxbContext.createUnmarshaller();

        Information information = (Information)jaxbMarshaller.unmarshal(new File("information.xml"));
        System.out.println(information);
    }
}

上面的输出是:

Information(customerId=null, billingAddressId=address1)

显然输出不正确。 customerId 显示 null 而不是 customer1。但是,如果我在 pojo 类中注释掉第 (2) 行,那么 customerId 将获得正确的值。为什么会这样?为什么我不能在上面的程序中读取正确的customerId 值?

【问题讨论】:

    标签: java xml xpath moxy


    【解决方案1】:

    从第二个 XmlPath 中删除 [@id='customer1'] 确实解决了所提供代码的问题,即使我假设真正的 Information 实体有更多字段,您可以使用 XmlPath 处理。

    为什么不使用一些类来反映 XML 结构……有点像面向对象?它将简化 JAXB 建模。

    【讨论】:

    • 谢谢。我最终为那个 XPATH 创建了一个 POJO。
    猜你喜欢
    • 2012-06-24
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 2016-08-21
    • 2012-01-14
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    相关资源
    最近更新 更多