我试图在swift中获取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
}
}
答案 0 :(得分:0)
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
组合成一个,但上面的内容更容易调试。
答案 1 :(得分: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)
}