gpt4 book ai didi

java - MOXy @XmlPath 注释无法多次读取相同的 XPath

转载 作者:行者123 更新时间:2023-12-02 11:43:34 26 4
gpt4 key购买 nike

我一直在努力使下面的程序工作,但我的代码或 @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 值?

最佳答案

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

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

关于java - MOXy @XmlPath 注释无法多次读取相同的 XPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48372354/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com