views:

33

answers:

3

hi

i have a string:

<presence to="[email protected]/d9ec56e4"
from="[email protected]/testsubject_2">
<x xmlns="http://jabber.org/protocol/muc#user"&gt;&lt;item affiliation="none"
role="visitor"/></x></presence>

how would i find out if it contains the presence attribute as well as who its from? ive tried using as3's xml methods but they require that the xml is a complete document so i figure to use regex but its late and im lost so ill post before i go to sleep :)

if (string contains <presence to="){
    // get who its from
}
A: 

/<(\w+)(( to|from)=\"([^\"]+)\")+>.*</\1>/

guilin 桂林
A: 

Search for: /<presence\b(?=[^><]*\sto\s*=)[^><]*\sfrom\s*=\s*["']([^><"']*)["'].*?</presence>/gis

$1 will refer to who its from, e.g. [email protected]/testsubject_2

It works even if to/from in a different order. It works even if XML uses single quotes, but there must not be a single-quotes between single-quotes. I can improve this behaviour further, but the regex would become longer.

If you take malformed XML documents into account, you shouldn't use regex, use either DOM or XPath instead.

Vantomex
I made a typo, and have edited the regex a bit.
Vantomex
Won't work if the XML uses single quotes. Won't work if to/from in a different order. Won't work if an attribute contains > (which is well-formed, according to the AttValue production of http://www.w3.org/TR/REC-xml/). XML is harder than it looks.
Joe Hildebrand
I have just edited the regex again to fulfil the most of your request.
Vantomex
+1  A: 

ARGH! I would highly recommend you don't use regex to parse XML, that's why we have XML parsers.

var raw_data:String = '<presence to="[email protected]/d9ec56e4" from="[email protected]/testsubject_2"> <x xmlns="http://jabber.org/protocol/muc#user"&gt;&lt;item affiliation="none" role="visitor"/></x></presence>';
trace("raw_data:", raw_data);
var presence:XML = new XML(raw_data);
trace("presence:", presence);
trace("root name == presence:", (presence.localName() == "presence")); // [trace] root name == presence: true
trace("from:", presence.@from); // [trace] from: [email protected]/testsubject_2

http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/XML.html

Or just use one of the many XMPP libraries out there:

http://code.google.com/p/as3xmpp/

http://code.google.com/p/seesmic-as3-xmpp/

Joony
in this circumstance, this method does not work. xmpp exchanges stanzas, not complete xml documents (or structure type). if you do this you will get TypeError: Error #1085: The element type "stream" must be terminated by the matching end-tag "</stream>".
lostinavoidofcompletelostness
Don't put the stream:stream start tag into the parser then, or use a SAX or pull parser.
Joe Hildebrand
A SAX parser would work. Is there an AS3 SAX parser?
Joony