2

我正在尝试快速获取 XML 节点中属性的值。下面是一个代码示例。我看不到任何获取值的方法,因为似乎没有属性或方法允许这样做。

for word in dictionary.words {
    let xpath = "/strongsdictionary/entries/entry[greek[@unicode='" + word.word + "']]/pronunciation"
    do {
        let xmlnode = try document?.nodes(forXPath: xpath )
        // Need to get value of attribute named 'strongs' from the node here.
    } catch {
        debugPrint("Error finding xpath path.")
        break
    }
}
4

2 回答 2

1

xmlnode是一个数组XMLNode。迭代节点数组。如果您的 xpath 返回元素,则将每个节点转换为XMLElement. 您可以从元素中获取其属性。

let xmlnodes = try document?.nodes(forXPath: xpath)
for node in xmlnodes {
    if let element = node as? XMLElement { 
        if let strongsAttr = element.attribute(forName: "strongs") {
            if let strongs = strongsAttr.stringValue {
                // do something with strongs
            }
        }
    }
}

您可以将三者合二为一,if let但以上更容易调试。

于 2018-03-30T20:47:53.593 回答
0

属性只是另一个节点。更改您的 XPath 表达式以找到它:

let xpath = "/strongsdictionary/entries/entry[greek[@unicode='" + word.word + "']]/pronunciation/@strongs"

.nodes方法返回节点列表。确保列表不是 nil 并且有一个节点:

    // Get value of attribute named 'strongs'
    if let xmlnode = try document?.nodes(forXPath: xpath ), xmlnode.count == 1 {
        print(xmlnode[0].objectValue)
    }
于 2018-03-30T20:51:02.253 回答