首页 > 解决方案 > 如何从 Swift 中的 [DDXMLElement] 中提取值?

问题描述

我想在节标签中提取 id 的值。
节标签是:

[<stanza-id xmlns="urn:xmpp:sid:0" by="f.talebi@wepod.ir" id="1531235744929009"></stanza-id>]

这是从 Xmpp 服务器接收到的消息的一部分。
我需要提取“1531235744929009”值。因此,我写了这个:

var stanza = message.elements(forName: "stanza-id")
print(stanza)
var id = stanza.first?.attributes
if let attributes = stanza.first?.attributes {
     let lastItem = attributes.last
     if let stanzaID = lastItem?.stringValue {
          print("stanzaID = \(stanzaID)")
     }
}

此代码工作正常,但它不是一个干净的代码。特别是在我写这行lastItem = attributes.last的地方,因为如果订单发生变化,这将不起作用。

标签: swiftxml

解决方案


只需使用stanza.attributed(forName: String)


推荐阅读