如何在java中的XML标记中打印值

时间:2014-03-26 12:10:17

标签: java xml

我从来不知道如何使用XML标记。如何遍历节点并在XML标记中打印特定节点.Below是XML文件。

<Employees>
<Employee>
    <Gender></Gender>
    <Name>
        <Firstname></Firstname>
        <Lastname></Lastname>
    </Name>
    <Email></Email>
    <Projects>
        <Project></Project>
    </Projects>
    <PhoneNumbers>
        <Home></Home>
        <Office></Office>
    </PhoneNumbers>
</Employee>

没有数据,但这是结构。我使用以下代码来部分解析它。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document xmlDocument = builder.parse("employees.xml");
System.out.println(xmlDocument.getDocumentElement().getNodeName());

我想打印性别和姓氏值。如何解析Name标签内的标签,而标签又在Employee标签内。

问候。

2 个答案:

答案 0 :(得分:0)

你应该使用XPATH。 this post中有一个很好的解释。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(<xpath_expression>);

答案 1 :(得分:0)

试试这个。

    String expression = "/Employees/Employee/Gender"; //read Gender value

    NodeList nList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
    for (int j = 0; nList != null && j < nList.getLength(); j++) {
        Node node = nList.item(j);
        System.out.println("" + node.getFirstChild().getNodeValue());
    }

    expression = "/Employees/Employee/Name/Lastname"; //read Lastname value

    nList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
    for (int j = 0; nList != null && j < nList.getLength(); j++) {
        Node node = nList.item(j);
        System.out.println("" + node.getFirstChild().getNodeValue());
    }