2014-03-26 96 views
0

XML标签内的值我从来没有真正知道如何使用XML tags.How我遍历节点,在XML tag.Below打印特定节点是XML文件。如何打印在java中

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

没有数据,但是这是我structure.I使用下面的代码来部分地解析它。

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

我想打印的性别和名字values.How做我分析这是名称标签,其名字依次是雇员标签内里的标签。

问候。

回答

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>); 
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()); 
    }