从Swift中的XML节点获取属性值

时间:2018-03-30 19:47:59

标签: swift xml nsxmlnode

我试图在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
    }
}

2 个答案:

答案 0 :(得分:0)

xmlnodeXMLNode的数组。迭代节点数组。如果您的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)
    }