2

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
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
doodle
  • 47
  • 7

2 Answers2

1

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks so much! Your an ace. That did the trick. It was not that obvious to me from reading the scetchy documentation. – doodle Mar 30 '18 at 21:17
  • Glad to help. Please don't forget to accept an answer that properly answers your question. Click the checkmark to the left of the answer. – rmaddy Mar 30 '18 at 21:25
0

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)
    }
Mike Taverne
  • 9,156
  • 2
  • 42
  • 58
  • I could find it that way but I couldn't figure out how to get the value out of it. Thanks for the help. – doodle Mar 30 '18 at 23:57