簡體   English   中英

Java XML 檢查節點是否存在

[英]Java XML check if node exists

我有 Java 和 XML 的問題。 我有一個注冊表單,將新用戶保存在文件 users.xml 中,我想在保存當前用戶之前檢查是否存在具有相同用戶名的另一個用戶。

這是我的 XML:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<user id="1">
<username>John</username>
<password>mypassword</password>
</user>

這是我的代碼:

public class isUserExisting {

public static boolean checkIfExists(String username) {

    try {   
         File inputFile = new File("src/users.xml");
         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
         Document doc = dBuilder.parse(inputFile);


         System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
         NodeList nList = doc.getElementsByTagName("user");
         System.out.println("----------------------------");


         for (int temp = nList.getLength() - 1; temp >= 0 ; temp--) {
            Node nNode = nList.item(temp);
            System.out.println();

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {     

               Element eElement = (Element) nNode;


               String tempUser = eElement.getElementsByTagName("username").item(0).getTextContent();

               if(tempUser == username) {
                   return true;
                   }
               else {
                   return false;
               }
            }


         }
      } catch (Exception e) {
         e.printStackTrace();
      }

    return false;
}

}

但每次我使用:

if(isUserExisting.checkIfExists(username)) {
System.out.println("This username exists");
}

我收到以下錯誤:

[Fatal Error] users.xml:6:2: The markup of the document that follow the element must have a correct format. 
org.xml.sax.SAXParseException; systemId: file:/eclipse/workspace/Folder/src/users.xml; lineNumber: 6; columnNumber: 2; The markup of the document that follow the element must have a correct format. 

有什么問題? 提前致謝 :)

對我來說運行正常。 我沒有收到Fatal Error

要使其正常工作,您需要將字符串與equals()方法正確比較:替換

if(tempUser == username)

if (tempUser.equals(username))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM