Java 如何在JAXB中从xpath返回值

Java 如何在JAXB中从xpath返回值,java,xml,xpath,jaxb,Java,Xml,Xpath,Jaxb,我还是JAXB新手,下面是我的代码清单 我的意图是使用以下示例打印这个xpath//customers/customer/name 我一直试图从@Blaise Doughan的博客中理解,但它总是给我一个空洞的结果。任何人都可以指出我的错误在哪里,我应该怎么做 示例XML <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <customers> <customer id="100">

我还是JAXB新手,下面是我的代码清单

我的意图是使用以下示例打印这个xpath//customers/customer/name

我一直试图从@Blaise Doughan的博客中理解,但它总是给我一个空洞的结果。任何人都可以指出我的错误在哪里,我应该怎么做

示例XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customers>
    <customer id="100">
        <name>customer1</name>
        <age>29</age>
    </customer>
    <customer id="200">
        <age>39</age>
        <name>customer2</name>
    </customer>
</customers>
客户名单

package performancetest.JAXB_Unmarshalling;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "customers")

public class CustomerNamesList {

    @XmlElement(name="customer/name")
    private List<CustomerNames> customerNamesList = new ArrayList<CustomerNames>();

    public List<CustomerNames> getCustomers() {
        return customerNamesList;
    }

    public void Customers(List<CustomerNames> CustomerNames) {
        this.customerNamesList = CustomerNames;
    }

    public void getElement () {
        for (int i=0; i<customerNamesList.size(); i++){
            System.out.println("Element "+i+": "+customerNamesList.get(i));
        }
    }
}
结果:

run:
[]
BUILD SUCCESSFUL (total time: 1 second)

我发现使用以下方法更容易做到这一点:

private String getXPath(String xml) throws XPathExpressionException {

    String xPathResult= "";
    InputSource source = new InputSource(new StringReader(xml));

    XPath xpath = XPathFactory.newInstance().newXPath();
    Object jaxBObject = xpath.evaluate("/customers", source, XPathConstants.NODE);

    xPathResult= xpath.evaluate("name", jaxBObject);

    return xPathResult;
}
这将为您提供name元素中的值。我希望这是有用的

run:
[]
BUILD SUCCESSFUL (total time: 1 second)
private String getXPath(String xml) throws XPathExpressionException {

    String xPathResult= "";
    InputSource source = new InputSource(new StringReader(xml));

    XPath xpath = XPathFactory.newInstance().newXPath();
    Object jaxBObject = xpath.evaluate("/customers", source, XPathConstants.NODE);

    xPathResult= xpath.evaluate("name", jaxBObject);

    return xPathResult;
}