简体   繁体   English

如何通过脚轮生成的 object 在 XML 中按属性值查找元素

[英]How to find an element by attribute value in XML via castor generated object

I am having trouble looking up elements by attribute value in the XML file via castor generated classes.我无法通过 castor 生成的类在 XML 文件中按属性值查找元素。

Castor does the mapping of XML to entity classes very good. Castor 很好地将 XML 映射到实体类。 However it doesn't provide means to find the element by name (assume that name is an attribute of the element).但是它不提供按名称查找元素的方法(假设名称是元素的属性)。 The API can only find an element by its index in the element list. API 只能通过元素列表中的索引找到一个元素。 At the moment it seems if I want to find an element by name I have to loop through the element list to find it.目前,如果我想按名称查找元素,我必须遍历元素列表才能找到它。 Because every class it unmarshalled has different fields it seems hard to write a generic method to find an element by name.因为它解组的每个 class 都有不同的字段,所以似乎很难编写通用方法来按名称查找元素。 Is there a better way to find an element from the element list by name?有没有更好的方法从元素列表中按名称查找元素?

Note: I'm the EclipseLink JAXB (MOXy) lead, and a member of the JAXB ( JSR-222 ) expert group.注意:我是EclipseLink JAXB (MOXy)负责人,也是 JAXB ( JSR-222 ) 专家组的成员。


Not sure about Castor, but you can do this easy enough with EclipseLink JAXB (MOXy) .不确定 Castor,但您可以使用EclipseLink JAXB (MOXy)轻松做到这一点。

Customer顾客

Note how a condition [@name='address'] is specified on the mapping via the @XmlPath annotation:请注意如何通过@XmlPath注释在映射上指定条件[@name='address']

package blog.predicate;

import java.util.List;

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

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

@XmlRootElement(name="node")
@XmlType(propOrder={"firstName", "lastName", "address", "phoneNumbers"})
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    @XmlPath("node[@name='first-name']/text()")
    private String firstName;

    @XmlPath("node[@name='last-name']/text()")
    private String lastName;

    @XmlPath("node[@name='address']")
    private Address address;

    @XmlPath("node[@name='phone-number']")
    private List<PhoneNumber> phoneNumbers;

}

XML XML

<?xml version="1.0" encoding="UTF-8"?>
<node>
   <node name="first-name">Jane</node>
   <node name="last-name">Doe</node>
   <node name="address">
      <node name="street">123 A Street</node>
   </node>
   <node name="phone-number" type="work">555-1111</node>
   <node name="phone-number" type="cell">555-2222</node>
</node>

For More Information了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM