2011-08-18 50 views
2

请注意,这不是我询问的另一个问题的重复,“With MOXy and XPath, is it possible to unmarshal a list of attributes?”它是相似的,但不一样。使用MOXy和XPath,是否可以解组两个属性列表?

我有XML,看起来像这样:

<test> 
    <items> 
    <item type="cookie" brand="oreo">cookie</item> 
    <item type="crackers" brand="ritz">crackers</item> 
    </items> 
</test> 

这类似于我先前讨论的XML除了现在有每个项目,而不是一两个属性。

在我的课:

@XmlPath("items/item/@type") 
@XmlAttribute 
private ArrayList<String> itemList = new ArrayList<String>(); 
@XmlPath("items/item/@brand") 
@XmlAttribute 
private ArrayList<String> brandList = new ArrayList<String>(); 

感谢回答我刚才的问题我可以给type属性解组到列表中。然而,brandList是空的。如果我注释掉注释itemList(所以它不是由JAXB/MOXy填充),那么brandList包含正确的值。

看来我只能使用XPath将单个属性解组到列表中。这是由设计还是我配置了错误的东西?

更新:看来我不能解组文本和元素的属性。如果我的类映射是这样的:

@XmlPath("items/item/text()") 
@XmlElement 
private ArrayList<String> itemList = new ArrayList<String>(); 
@XmlPath("items/item/@brand") 
@XmlAttribute 
private ArrayList<String> brandList = new ArrayList<String>(); 

brandList也是在这种情况下是空的。如果我切换订单并先映射brandList,则itemList为空。就好像第一个映射消耗元素,所以基于该元素或其属性的更多值不能被读取。

+0

你有最新版本的Moxy吗?我遇到了一些使用旧版本(在更新到最新版本时消失)的XPath属性过滤错误。 – Thilo

+0

我有几个星期前下载的EclipseLink 2.3。根据他们的下载页面,v2.3似乎是最新的。 – Paul

+0

该配置目前不会给你你正在寻找的输出。我会尽量把你可以使用的替代方案放在一起。注意:我是EclipseLink JAXB(MOXy)的领导者。 –

回答

1

简答

这不是在EclipseLink MOXy与@XmlPath目前支持的使用情况。我已经进入了这个以下增强请求,随意添加附加信息,把票投给了这个bug:

长的答案

莫西将支持映射:

@XmlPath("items/item/@type") 
private ArrayList<String> itemList = new ArrayList<String>(); 

去:

<test> 
    <items> 
    <item type="cookie"/> 
    <item type="crackers"/> 
    </items> 
</test> 

但不是:

@XmlPath("items/item/@type") 
private ArrayList<String> itemList = new ArrayList<String>(); 

@XmlPath("items/item/@brand") 
private ArrayList<String> brandList = new ArrayList<String>(); 

到:

<test> 
    <items> 
    <item type="cookie" brand="oreo"/> 
    <item type="crackers" brand="ritz"/> 
    </items> 
</test> 

解决方法

你可以引入一个中间目标(Item)来映射这个用例:

@XmlElementWrapper(name="items") 
@XmlElement(name="item") 
private ArrayList<Item> itemList = new ArrayList<Item>(); 

 

public class Item { 

    @XmlAttribute 
    private String type; 

    @XmlAttribute 
    private String brand; 
} 

的更多信息,@XmlPath

+0

非常感谢!你知道一个很好的资源,我可以学习如何以及何时使用'@ XmlAttribute','@ XmlElement'等?如果我不小心将另一个替换为另一个,或者即使在使用'@ XmlPath'时将其忽略,我也没有注意到它们之间的区别。 – Paul

+1

@Paul - 不确定我可以指示你的具体资源。如果你使用'@ XmlPath',那么你不需要使用'@ XmlAttribute'或'@ XmlElement'。也注释字段或属性很重要,以下可能会有所帮助:http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html。 –

+0

仍然不支持用例吗?我需要一个java类中的一些xml元素在同一个分组下。我正在使用xpath添加分组标记。但是我怎样才能在同一个子标签下带来多种元素? – Aparna

相关问题