2014-03-25 140 views
0

我有一個xml文件,我用XPATH解析它。但我同時獲得內容出來的Xpath沒有給出正確的結果

這裏有問題是XML

<?xml version='1.0' encoding='UTF-8' standalone='yes' ?> 
<reg> 
    <user> 
    <Name>abc def</Name> 
    <Email>ahjkhjkghjkhjk</Email> 
    <Picture>/mnt/sdcard/download/1357670177a386a-big-1.jpg</Picture> 
    <LastEdited>Mar 12, 2014 10:32:09 AM</LastEdited> 
    </user> 
    <user> 
    <Name>xy zabc</Name> 
    <Email>asdasdasdasd</Email> 
    <Picture>/mnt/sdcard/download/1357670177a386a-big-1.jpg</Picture> 
    <LastEdited>Mar 12, 2014 10:32:09 AM</LastEdited> 
    </user> 
    </reg> 

,這裏是我的代碼用於解析它

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 

DocumentBuilder builder = builderFactory.newDocumentBuilder(); 

Document xmlDocument = builder.parse(file); 

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


String expression = "/reg/user/Name"; 
System.out.println(expression); 

NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET); 
for (int i = 0; i < nodeList.getLength(); i++) { 
    System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
    Users_List.add(nodeList.item(i).getFirstChild().getNodeValue()); 
} 

這種表達"reg/user"它返回任何結果和"reg/user/Name""reg/user/Email"它會返回正確的結果。我已經用在線測試器測試了表達式,它給出了正確的結果。有我的解析代碼螞蟻問題..?

回答

1

您的每個user元素的第一個子元素都是空的文本節點,因此您的println語句可能只是不打印任何內容。這給一試:

for (int i = 0; i < nodeList.getLength(); i++) { 
    System.out.println(nodeList.item(i).getChildNodes()[1].getTextContent()); 
    Users_List.add(nodeList.item(i).getChildNodes()[1].getTextContent()); 
} 

儘管這可能是更好的:

for (int i = 0; i < nodeList.getLength(); i++) { 
    String name = ""; 
    NodeList nameList = (NodeList)xPath.evaluate("Name", nodeList.items(i), 
                XPathConstants.NODE); 
    if(nameList.getLength() > 0) { 
     name = nameList.items(0).getTextContent(); 
    } 
    System.out.println(name); 
    Users_List.add(name); 
} 
+0

還是同樣的結果。 。 。 –

+1

使用getTextContent()代替getNodeValue() – Fireworks

+0

@Fireworks:感謝它的工作:) –