Reputation: 47
I am trying to get the value of an attribute in an XML Node in swift. The following is a code example. I don't see any way of getting the value as no properties or methods seem to allow for this.
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
}
}
Upvotes: 2
Views: 2466
Reputation: 9352
An attribute is just another node. Change your XPath expression to find it:
let xpath = "/strongsdictionary/entries/entry[greek[@unicode='" + word.word + "']]/pronunciation/@strongs"
The .nodes
method returns a list of nodes. Make sure the list is not nil and has one node:
// Get value of attribute named 'strongs'
if let xmlnode = try document?.nodes(forXPath: xpath ), xmlnode.count == 1 {
print(xmlnode[0].objectValue)
}
Upvotes: 0
Reputation: 318774
xmlnode
is an array of XMLNode
. Iterate the array of nodes. If your xpath returns elements, then cast each node to an XMLElement
. From the element you can get the its attributes.
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
}
}
}
}
You can combine the three if let
into one but the above is easier to debug.
Upvotes: 1