XMPP:如何解析XMPPMessage元素

问题描述 投票:0回答:2

我为来自xmpp的每条消息获取以下xml格式

- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
 NSLog(@"Message %@",message);        
}

在控制台中打印

<message
    xmlns="jabber:client" from="[email protected]" to="[email protected]/mobile">
    <result
        xmlns="urn:xmpp:mam:tmp" id="1483781596098940">
        <forwarded
            xmlns="urn:xmpp:forward:0">
            <message
                xmlns="jabber:client" from="[email protected]/mobile" to="[email protected]" type="chat">
                <body>Hi</body>
                <delay
                    xmlns="urn:xmpp:delay" from="xmpp-dev.peeks.com" stamp="2016-12-22T04:50:17.023Z">Offline Storage
                </delay>
            </message>
            <delay
                xmlns="urn:xmpp:delay" from="xmpp-dev.peeks.com" stamp="2017-01-07T09:33:16.099Z">
            </delay>
        </forwarded>
    </result>
</message>

我想从每条消息中获取“from”,“to”,“body”和“stamp”,我做了以下操作

NSXMLElement *body = message;
    NSXMLElement *messageb  = [body elementForName:@"result" xmlns:@"urn:xmpp:mam:tmp"];
    NSXMLElement *forwa=[messageb elementForName:@"forwarded" xmlns:@"urn:xmpp:forward:0"];
    NSXMLElement *msg=[forwa elementForName:@"message" xmlns:@"jabber:client"];
    NSXMLElement *TD=[forwa elementForName:@"delay" xmlns:@"urn:xmpp:delay"];

    NSString *from=[[msg elementForName:@"from" xmlns:@"jabber:client"] stringValue];
    NSString *to=[[msg elementForName:@"to" xmlns:@"jabber:client"] stringValue];
    NSString *bodyq=[[msg elementForName:@"body"] stringValue];
    NSString *stmp=[[TD elementForName:@"stamp" xmlns:@"urn:xmpp:delay"] stringValue];
    NSString *final=[NSString stringWithFormat:@"From: %@\nTo: %@\nBody: %@\nStamp: %@",from,to,bodyq,stmp];
    NSLog(@"forwa %@", final);

我只能打印邮件正文和日志打印

From: (null)
To: (null)
Body: hi
Stamp: (null)
objective-c xmpp nsxmlelement
2个回答
1
投票

修复搜索属性:元素是节点(如Body,Result等),而其他元素只是以前元素的属性。

NSString *from=[[msg attributeForName:@"from"] stringValue];
    NSString *to=[[msg attributeForName:@"to"] stringValue];
    NSString *stmp=[[TD attributeForName:@"stamp"] stringValue];

编辑(对不起,我上次与ObjectiveC合作的时候真的很老了)。

xml namespace它是关于element而不是attributes

如果你没有再次尝试,请尝试通过NSXMLNode

NSXMLNode *fromNode = [msg attributeForName:@"from"];
NSString *from = [fromNode stringValue];

1
投票

对于快速5:

func xmppStream(_ sender: XMPPStream, didReceive message: XMPPMessage) {
        if let msg = message.body {
            if let from = message.attribute(forName: "from")?.stringValue{
                print("msg: \(msg), \(from)")
            }
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.