2017-05-11 37 views
0

我有一個XML文件,名爲feed.xml,我正在使用JAVA上的DOM包來取消數據。使用Java在XML DOM上使用getElementsByTagName()值的IF語句

我能夠成功地取消數據,現在我需要能夠創建IF語句,這取決於我從XML獲得的數據。

我的問題是,即使強硬我分配一個字符串變量的屬性數據,當我使用IF進行比較時,條件返回FALSE,當它應該是正確的。

這是我的一些XML的

<inventory> 
    <item UnitID="1234" Record="0"> 
     <id>1234</id> 
     <dealerid>455</dealerid> 
     <stock_number>1600Xtreme</stock_number> 
     <make>Nvidia</make>      
    </item> 
    <item UnitID="7854" Record="1"> 
     <id>7854</id> 
     <dealerid>587</dealerid> 
     <stock_number>12TMAX5500</stock_number> 
     <make>Realtek</make> 
    </item> 
</inventory> 

這是我的一些Java代碼刮數據,也IF語句我假裝使用方法:

File fXmlFile=new File("feed.xml"); 
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance(); 
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder(); 
Document doc=dBuilder.parse(fXmlFile); 
doc.getDocumentElement().normalize(); 
NodeList nList=doc.getElementsByTagName("item"); 
for (int temp=0; temp < nList.getLength(); temp++) 
{ 
    Node nNode=nList.item(temp); 
    Element eElement2=(Element)nNode; 
    String search="Nvidia"; 
    System.out.println("This is the value to search from my variable: " + 
    search); //This prints Nvidia 
    String toTest=(eElement2.getAttribute("make")); 
    System.out.println("toTest is equal to: " + toTest); //This prints 
    Nvidia 
    if (toTest == search) 
    { 
     System.out.println("The condition on the IF is True"); 
    } 
} 

我應該得到的輸出: 「IF上的條件爲真」

但是我沒有得到什麼,因爲根據JAVA不是TRUE。

我已經研究和嘗試了許多不同的方法來進行比較,但似乎沒有任何工作。 (它對我有效,如果我比較整數,但在這種情況下是一個字符串)我感謝您的答案。

回答

0

比較對象時想使用.equals==將不會爲String返回true,即使它們包含相同的信息,因爲==通過引用進行比較,而.equals按值進行比較。

因此將其更改爲if (toTest.equals(search))

0

UnitIDRecorditem節點的屬性。 make是一個子節點到item節點。因此,您需要獲取「make」節點上的文本內容才能檢索其值。嘗試下面的代碼:

File fXmlFile=new File("feed.xml"); 
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance(); 
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder(); 
Document doc=dBuilder.parse(fXmlFile); 
doc.getDocumentElement().normalize(); 
NodeList nList=doc.getElementsByTagName("item"); 

for (int temp=0; temp < nList.getLength(); temp++) 
    { 
     Node nNode=nList.item(temp); 
     if (nNode.getNodeType() == Node.ELEMENT_NODE) { 
      NodeList children = nNode.getChildNodes(); 
      for(int i = 0; i < children.getLength(); i++) { 
       Node childNode = children.item(i); 
       if (childNode.getNodeName() == "make"){ 
        String make = childNode.getTextContent(); 
        if ("Nvidia".equals(make)) { 
         System.out.print(childNode.getTextContent()); // This will print Nvidia 
        } 
       } 
      } 
     } 
    }