使用xPath从xml文件创建Java对象

时间:2016-04-14 11:00:04

标签: java xml xpath

我有一个这种格式的xml文件:

<Employee>
    <EmployeeID>10</EmployeeID>
    <Name>David</Name>
    <Department>Service</Department>
</Employee>

我有一个大的xml文件,只包含这种格式的员工。我想要的是使用xPath从文件中选择节点,然后为每个条目创建一个Java对象:

public class Employee {

String name; 
String department; 
int age; 

public int getAge() {
    return age; 
}

public void setAge(int age) {
    this.age = age; 
}

public String getName() {
    return name; 
}

public void setName(String name) {
    this.name = name; 
}

public String getDepartment() {
    return department; 
}

public void setDepartment(String department) {
    this.department = department; 
}

}

这是我到目前为止所拥有的。我似乎无法弄清楚如何最好地检索我需要的所有信息,并创建对象:

public void parseFile(String fileName) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    Document document = null;

    try {
        builder = factory.newDocumentBuilder();
        document = builder.parse(new File(fileName));

        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();

        List<Employee> employees = getEmployeesFromXml(document, xPath); 

    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private List<Employee> getEmployeesFromXml(Document document, XPath xPath) {

    List<Employee> list = new ArrayList<Employee>();

    try {
        // Create an expression that retrieves the values from xml 
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return null;
}

1 个答案:

答案 0 :(得分:1)

如果您不想解析XML并对节点执行某些操作,只将它们转换为Java对象,我建议您查看XMLBeam。这是一个很好的框架,它可以加载您的XML文件,并根据您为每个元素定义的XPath创建投影。

例如,这是投影的样子:

public interface ProfileData {
    @XBRead("/root/personal_data/resultSet/firstname")
    String getFirstName();
    @XBRead("/root/personal_data/resultSet/surname")
    String getSurname();

    @XBRead("/root/personal_data/resultSet/core_areas")
    String getCoreAreas();

    interface Skill {
        @XBRead("skillname")
        String getName();
        @XBRead("skillval")
        String getExperience();
    }
    interface SkillSet {
        @XBRead("../gencatname")
        String getGenericCategory();
        @XBRead("catname")
        String getCategory();
        @XBRead("skill")
        List<Skill> getSkills();
    }

    @XBRead("/root/skills/tab/category")
    List<SkillSet> getSkillSets();
}

@XBRead注释定义XPath收集元素的位置。

要提取信息,您可以像这样调用XMLBeam:

ProfileData profileData = new XBProjector().io().stream(yourXMLFileStream).read(ProfileData.class);