微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用带有@XmlElementRefs 注释的 XJC 生成的类读取 XML 文件

如何解决使用带有@XmlElementRefs 注释的 XJC 生成的类读取 XML 文件

我使用 XJC 创建了 JAXB 类,并且很多类都包含 @XmlElementRefs。 (我知道这是我用的xsd方案造成的,我没问题)

例如:

@XmlRootElement(name = "enfinity",namespace = "http://www.company.com/xml/ns/enfinity/7.0/xcs/impex")
public class Enfinity {

    @XmlElementRefs({

        @XmlElementRef(name = "offer",namespace = "http://www.company.com/xml/ns/enfinity/7.0/xcs/impex",type = JAXBElement.class,required = false),@XmlElementRef(name = "category",@XmlElementRef(name = "product",required = false)
    })
    protected List<JAXBElement<?>> categoryOrProductOrOffer;
....

生成了更多类,例如 ComplexTypeProduct,它是上述类中“产品”、“类别”和“报价”的类型:

public class ComplexTypeProduct {
    @XmlElementRefs({
        @XmlElementRef(name = "sku",@XmlElementRef(name = "custom-attributes",@XmlElementRef(name = "long-description",required = false)
    })
    protected List<JAXBElement<?>> availableOrImageOrThumbnail;

生成更多生成的类,例如 ComplexTypeCustomAttribute,它是上述类中“自定义属性”的类型:

public class ComplexTypeCustomAttribute {

    @XmlElementRef(name = "value",required = false)
    @XmlMixed
    protected List<Serializable> content;
    @XmlAttribute(name = "name",required = true)

这只是生成代码的一部分。

现在我有两个问题:

  1. 我知道例如 ComplexTypeProduct 是 XML 元素产品的类型。但是我通过阅读我用来生成类的 xsd 模式知道这一点。但是我怎样才能在生成的类中找到它?

  2. 什么是将 XML 读入生成的类的好习惯。例如,是否可以通过查看 getDeclaredType() 或 getLocalPART 来了解我正在处理正确的 XML 元素?

Enfinity um = (Enfinity) unmarshaller.unmarshal(new File("data/more_products.xml"));
List<JAXBElement<?>> products = um.getCategoryOrProductOrOffer();

products.forEach(product->
{
    if (product.getDeclaredType().equals(ComplexTypeProduct.class))
    {
        ComplexTypeProduct complexTypeProduct = (ComplexTypeProduct)product.getValue();
        List<JAXBElement<?>> productAttributes = complexTypeProduct.getAvailableOrImageOrThumbnail();
        productAttributes.forEach(attribute->
        {
            if (attribute.getName().getLocalPart().equals("custom-attributes"))
            {
                ComplexTypeCustomAttributes complexTypeCustomAttributes = (ComplexTypeCustomAttributes)attribute.getValue();
                complexTypeCustomAttributes.getCustomAttribute().forEach(a-> System.out.println(a.getName()));
            }
        });
    }
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。