<p>I've been having some trouble parsing various types of XML within flash (specifically FeedBurner RSS files and YouTube Data API responses). I'm using a <code>URLLoader</code> to load a XML file, and upon <code>Event.COMPLETE</code> creating a new XML object. 75% of the time this work fine, and every now and again I get this type of exception:</p>

<pre><code>TypeError: Error #1085: The element type "link" must be terminated by the matching end-tag "&lt;/link&gt;".
</code></pre>

<p>We think the problem is that The XML is large, and perhaps the <code>Event.COMPLETE</code> event is fired before the XML is actually downloaded from the <code>URLLoader</code>. The only solution we have come up with is to set off a timer upon the Event, and essentially "wait a few seconds" before beginning to parse the data. Surely this can't be the best way to do this.</p>

<p>Is there any surefire way to parse XML within Flash?</p>

<p><strong>Update Sept 2 2008</strong> We have concluded the following, the excption is fired in the code at this point:</p>

<pre><code>data = new XML(mainXMLLoader.data);

//  calculate the total number of entries.
for each (var i in data.channel.item){
    _totalEntries++;
}
</code></pre>

<p>I have placed a try/catch statement around this part, and am currently displaying an error message on screen when it occurs. My question is how would an incomplete file get to this point if the <code>bytesLoaded == bytesTotal</code>?</p>

<hr>

<p>I have updated the original question with a status report; I guess another question could be is there a way to determine wether or not an <code>XML</code> object is properly parsed before accessing the data (in case the error is that my loop counting the number of objects is starting before the XML is actually parsed into the object)?</p>

<hr>

<p>@Theo: Thanks for the ignoreWhitespace tip. Also, we have determined that the event is called before its ready (We did some tests tracing <code>mainXMLLoader.bytesLoaded + "/" + mainXMLLoader.bytesLoaded</code></p>

[{'answer_id': 17963, 'author': 'Re0sless', 'author_id': 2098, 'author_profile': 'https://Stackoverflow.com/users/2098', 'pm_score': 1, 'selected': False, 'text': '<p>Have you tried checking that the bytes loaded are the same as the total bytes?</p>\n\n<pre><code>URLLoader.bytesLoaded == URLLoader.bytesTotal\n</code></pre>\n\n<p>That should tell you if the file has finished loading, it wont help with the compleate event firing to early, but it should tell you if its a problem with the xml been read.</p>\n\n<p>I am unsure if it will work over domains, as my xml is always on the same site.</p>\n'}, {'answer_id': 18337, 'author': 'vanhornRF', 'author_id': 1945, 'author_profile': 'https://Stackoverflow.com/users/1945', 'pm_score': 0, 'selected': False, 'text': '<p>As you mentioned in your question, the problem is very likely that your program is looking at the XML before it has actually been completely downloaded, I don\'t know that there\'s a surefire way to "parse" the XML because the parsing portion of your code is more than likely fine, it\'s simply a matter of whether or not it has actually downloaded.</p>\n\n<p>You could try to use the ProgressEvent.PROGRESS event to continually monitor the XML as it downloads and then as Re0sless suggested, check the bytesLoaded vs the bytesTotal and have your XML parse begin when the two numbers are equal instead of using the Event.COMPLETE event. </p>\n\n<p>You should be able to get the bytesLoaded and bytesTotal numbers just fine regardless of domains, if you can access the file you can access its byte information.</p>\n'}, {'answer_id': 18365, 'author': 'Brian Warshaw', 'author_id': 1344, 'author_profile': 'https://Stackoverflow.com/users/1344', 'pm_score': 1, 'selected': False, 'text': "<p>The concerning thing to me is that it might be firing Event.COMPLETE before it's finished loading, and that makes me wonder whether or not the load is timing out. </p>\n\n<p>How often does the problem happen? Can you have success one moment, then failure the very next with the same feed?</p>\n\n<p>For testing purposes, try tracing the <code>URLLoader.bytesLoaded</code> and the <code>URLLoader.bytesTotal</code> at the top of your <code>Event.COMPLETE</code> handler method. If they don't match, you know that the event is firing prematurely. If this is the case, you can listen for the URLLoader's progress event. Check the <code>bytesLoaded</code> against the <code>bytesTotal</code> in your handler and only parse the XML once the loading is truly complete. Granted, this is very likely akin to what the URLLoader is doing before it fires <code>Event.COMPLETE</code>, but if that's broken, you can try rolling your own.</p>\n\n<p>Please let us know what you find out. And if you could, please paste in some source code. We might be able to spot something of note.</p>\n"}, {'answer_id': 20037, 'author': 'Theo', 'author_id': 1109, 'author_profile': 'https://Stackoverflow.com/users/1109', 'pm_score': 0, 'selected': False, 'text': '<p>If you could post some more code we might be able to find the issue.</p>\n\n<p>Another thing to test (besides tracing <code>bytesTotal</code>) is to trace the <code>data</code> property of the loader in the <code>Event.COMPLETE</code> handler, just to see if the XML data was actually loaded correctly, for example check that there is a <code>&lt;/link&gt;</code> there.</p>\n'}, {'answer_id': 20639, 'author': 'Jeff Winkworth', 'author_id': 1306, 'author_profile': 'https://Stackoverflow.com/users/1306', 'pm_score': 0, 'selected': False, 'text': '<p>@Brian Warshaw: This issue happens only about 10-20% of the time. Sometimes it hiccups and simply reloading the app will work fine, other times I will spend half an hour reloading the app over and over again to no avail.</p>\n\n<p>This is the original code (when I asked the question):</p>\n\n<pre><code>public class BlogReader extends MovieClip {\n    public static const DOWNLOAD_ERROR:String = "Download_Error";\n    public static const FEED_PARSED:String = "Feed_Parsed";\n\n    private var mainXMLLoader:URLLoader = new URLLoader();\n    public var data:XML;\n    private var _totalEntries:Number = 0;\n\n    public function BlogReader(url:String){\n        mainXMLLoader.addEventListener(Event.COMPLETE, LoadList);\n        mainXMLLoader.addEventListener(IOErrorEvent.IO_ERROR, errorCatch);\n        mainXMLLoader.load(new URLRequest(url));\n        XML.ignoreWhitespace;\n    }\n    private function errorCatch(e:IOErrorEvent){\n        trace("Oh noes! Yous gots no internets!");\n        dispatchEvent(new Event(DOWNLOAD_ERROR));\n    }\n    private function LoadList(e:Event):void {\n        data = new XML(e.target.data);\n\n        //  calculate the total number of entries.\n        for each (var i in data.channel.item){\n            _totalEntries++;\n        }\n\n        dispatchEvent(new Event(FEED_PARSED));\n    }\n}\n</code></pre>\n\n<p>And this is the code that I wrote based on Re0sless\' original reply (similar to some suggestions mentioned):</p>\n\n<pre><code>public class BlogReader extends MovieClip {\n    public static const DOWNLOAD_ERROR:String = "Download_Error";\n    public static const FEED_PARSED:String = "Feed_Parsed";\n\n    private var mainXMLLoader:URLLoader = new URLLoader();\n    public var data:XML;\n    protected var _totalEntries:Number = 0;\n\n    public function BlogReader(url:String){\n        mainXMLLoader.addEventListener(Event.COMPLETE, LoadList);\n        mainXMLLoader.addEventListener(IOErrorEvent.IO_ERROR, errorCatch);\n        mainXMLLoader.load(new URLRequest(url));\n        XML.ignoreWhitespace;\n    }\n    private function errorCatch(e:IOErrorEvent){\n        trace("Oh noes! Yous gots no internets!");\n        dispatchEvent(e);\n    }\n    private function LoadList(e:Event):void {\n        isDownloadComplete();           \n    }\n    private function isDownloadComplete() {\n        trace (mainXMLLoader.bytesLoaded + "/" + mainXMLLoader.bytesLoaded);\n        if (mainXMLLoader.bytesLoaded == mainXMLLoader.bytesLoaded){\n            trace ("xml fully loaded");\n\n            data = new XML(mainXMLLoader.data);\n\n            //  calculate the total number of entries.\n            for each (var i in data.channel.item){\n                _totalEntries++;\n            }\n\n            dispatchEvent(new Event(FEED_PARSED));\n        } else {\n            trace ("xml not fully loaded, starting timer");\n            var t:Timer = new Timer(300, 1);\n            t.addEventListener(TimerEvent.TIMER_COMPLETE, loaded);\n            t.start();\n        }\n    }\n    private function loaded(e:TimerEvent){\n        trace ("timer finished, trying again");\n        e.target.removeEventListener(TimerEvent.TIMER_COMPLETE, loaded);\n        e.target.stop();\n\n        isDownloadComplete();\n    }\n}\n</code></pre>\n\n<p>I\'ll point out that since adding the code determining if <code>mainXMLLoader.bytesLoaded == mainXMLLoader.bytesLoaded</code> I have not had an issue - that said, this bug is hard to reproduce so for all I know I haven\'t fixed anything, and instead just added useless code.</p>\n'}, {'answer_id': 21928, 'author': 'Theo', 'author_id': 1109, 'author_profile': 'https://Stackoverflow.com/users/1109', 'pm_score': 1, 'selected': False, 'text': '<p>Just a side note, this statement has no effect:</p>\n\n<pre><code>XML.ignoreWhitespace;\n</code></pre>\n\n<p>because <code>ignoreWhitespace</code> is a property. You have to set it to <code>true</code> like this:</p>\n\n<pre><code>XML.ingoreWhitespace = true;\n</code></pre>\n'}, {'answer_id': 21929, 'author': 'Theo', 'author_id': 1109, 'author_profile': 'https://Stackoverflow.com/users/1109', 'pm_score': 0, 'selected': False, 'text': "<p>The <code>Event.COMPLETE</code> handler really shouldn't be called unless the loader was fully loaded, it makes no sense. Have you confirmed that it is in fact not fully loaded (by looking at the <code>bytesLoaded</code> vs. <code>bytesTotal</code> values that you trace)? If the <code>Event.COMPLETE</code> event is dispatched before <code>bytesLoaded == bytesTotal</code> that is a bug.</p>\n\n<p>Good that you've got it working with the timer, but it is very odd that you need it.</p>\n"}, {'answer_id': 25058, 'author': 'Theo', 'author_id': 1109, 'author_profile': 'https://Stackoverflow.com/users/1109', 'pm_score': 0, 'selected': False, 'text': '<p>I suggest that you file a bug report at <a href="https://bugs.adobe.com/flashplayer/" rel="nofollow noreferrer">https://bugs.adobe.com/flashplayer/</a>, because the event really shouldn\'t fire before all the bytes are loaded. In the meantime I guess you have to live with the timer. You might be able to do the same by listening at the progress event instead, that could perhaps save you from having to handle the timer yourself.</p>\n'}, {'answer_id': 132117, 'author': 'Brian Hodge', 'author_id': 20628, 'author_profile': 'https://Stackoverflow.com/users/20628', 'pm_score': 0, 'selected': False, 'text': '<p>You could set a unique element namespace at the very end of your XML document that has one attribute "value" equal to "true";</p>\n\n<pre><code>//The XML\n//Flash ignores the line that specifies the XML version and encoding so I have here as well.\n\n&lt;parent&gt;\n    &lt;child name="child1" /&gt;\n    &lt;child name="child2" /&gt;\n    &lt;child name="child3" /&gt;\n    &lt;child name="child4" /&gt;\n    &lt;documentEnd value="true" /&gt;\n&lt;/parent&gt;\n\n//Sorry about the spacing, but it is difficult to get XML to show.\n\n//Flash\nvar loader:URLLoader = new URLLoader();\nvar request:URLRequest = new URLRequest(\'pathToXML/xmlFileName.xml\');\n\nvar xml:XML;\n\n//Event Listener with weak reference set to true (5th parameter);\n//The above comment does not define a required practice, this is to aid with garbage collection.\n\nloader.addEventListener(Event.COMPLETE, onXMLLoadComplete, false, 0, true);\nloader.load(request);\nfunction onXMLLoadComplete(e:Event):void\n{\n   xml = new XML(e.target.data);\n\n   //Now we check the last element (child) to see if it is documentEnd.\n   if(xml[xml.length()-1].documentEnd.@value == "true")\n   {\n      trace("Woot, it seems your xml made it!");\n   }\n   else\n   {\n      //Attempt the load again because it seems it failed when it was unable to find documentEnd in the XML Object.\n      loader.load(request);\n   }\n}\n</code></pre>\n\n<p>I hope that this helps you for now, but the real hope is that enough people let adobe know about this issue.  It is a sad thing to not be able to rely on events.  I must say though, from what I have heard about XML, it is not very optimal at a large scale and believe this is when you require something like AMFPHP to serialize the data.</p>\n\n<p>Hope this helps!  Remember the idea here is that we know what the very last child/element in the XML is because we set it!  There is no reason that we shouldn\'t be able to access the last child/element, but if we cannot, we must assume that the XML was not indeed complete and we force it to load again.</p>\n'}, {'answer_id': 1287231, 'author': 'enzuguri', 'author_id': 61466, 'author_profile': 'https://Stackoverflow.com/users/61466', 'pm_score': 0, 'selected': False, 'text': '<p>sometimes the RSS server page can fail to spit out correct and valid XML data especially if your constantly hitting it, so it may not be your fault. Have you tried hitting the page in a web browser (preferably with an xml validator plugin) to check that the server response is always valid?</p>\n\n<p>The only other thing that I can see here is the line:</p>\n\n<pre><code>xml = new XML(event.target.data);\n\n//the data should already be XML, so only casting is necessary\nxml = XML(event.target.data);\n</code></pre>\n\n<p>Have you also tried setting the urlloader dataFormat to URLLoaderDataFormat.TEXT, and also adding url headers of prama-no-cache and/or adding a cache buster tot he url?</p>\n\n<p>Just some suggestions...</p>\n'}]
['https://Stackoverflow.com/questions/17911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306/']