2014-03-26 143 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()); 
    }