根据元素值来解析XML并检查值

  • 本文关键字:XML 元素 xml kotlin
  • 更新时间 :
  • 英文 :


我试图通过解析填充有用户的XML文件来验证用户的用户名和密码。目前,我的方法又回来了。它应该浏览<users>的子元素并使用给定的用户名找到用户,并根据checkUser()的参数检查密码。

我似乎无法访问<password>元素内部的文本。

这是我迄今为止尝试过的:

fun checkUser(username: String, password: String) : Boolean {
    val xmlFile = File("Users.xml")
    val doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile)
    var list = doc.getElementsByTagName("user")
    for (i in 0 until list.length) {
        var current = list.item(i)
        if (current.attributes.getNamedItem("id").nodeValue == username) {
            return current.lastChild.textContent == password //trying to check text against given password
        }
    }
    return false
}
fun main(args: Array<String>) {
    println(checkUser("alec", "123")) //returns false right now
}

这是我的XML文件:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<users>
    <user id="alec">
        <username>alec</username>
        <password>123</password>
    </user>
    <user id="john">
        <username>john</username>
        <password>415</password>
    </user>
</users>

编辑

current.attributes.item(0)返回一个节点,但是我需要在 <user> tag内获取属性 id并根据给定的用户名进行检查。

编辑修复代码以获取ID并与username参数进行比较,仍然返回False

如果返回的nodelist的大小,请致电current.childNodes,您将获得5。第一个,第三和最后一个节点是空白节点。您的数据在节点2和4中。因此,您可以用以下内容替换代码。

val xmlFile = File("Users.xml")
val doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile)
var list = doc.getElementsByTagName("user")
for (i in 0 until list.length) {
    var current = list.item(i)
    if (current.attributes.getNamedItem("id").nodeValue == username) {
        println(current.childNodes.length)
        for (j in 0 until current.childNodes.length) {
            if (current.childNodes.item(j).nodeName == "password") {
                return current.childNodes.item(j).textContent == password
            }
        }
    }
}
return false

也就是说,我很想使用更好的XML解析器,因为此代码的冗长远远超过所需的。

例如,使用DOM4J,您可以用

替换上述所有代码
val doc = SAXReader().read(File("users.xml"))
val users = doc.rootElement.elements("user")
for (user in users) {
    if (user.attribute("id").value == username) {
        return user.element("password").text == password
    }
}
return false

最新更新