swift - 如何从 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
的地方,因为如果订单发生变化,这将不起作用。
解决方案
只需使用stanza.attributed(forName: String)
推荐阅读
- java - 为什么这个 unban 命令总是给我 NullPointerException?
- riscv - 从零增加 AsIDBits
- javascript - 通过拖动水平滚动卡片列表
- amazon-cognito - 如何使用 Cognito 中 event.request.codeParameter 的值发送自定义电子邮件
- r - 如何根据另一列的值聚合两列的 R 数据框
- python - pygame中的瓷砖碰撞物理
- cryptography - Google Apps 脚本中的 FTX API 未进行身份验证
- python-3.x - 来自pytube的流媒体链接?
- python - PyTorch 卷积精度冻结
- angular - Angular 不会部署 Docker 桌面 + Kubernetes