开发者

Can not read xml data into flash

开发者 https://www.devze.com 2022-12-13 07:03 出处:网络
I write a simple xml code, and I try to read the xml file into flash, but I got \"undefined\" in my output.

I write a simple xml code, and I try to read the xml file into flash, but I got "undefined" in my output. The codes are as following. Do you know how to sove the problem? Thanks.

xml file (test.xml):

<?xml version='1.0' encoding='ISO-8859-1'?>
<note>
 <to>Tom</to>
 <from>Peter</from>
 <headin开发者_如何学Cg>Reminder</heading>
 <body>Don't forget me this weekend!</body>
</note>

Flash program:

xmlDoc=loadXMLDoc("test.xml");
x=xmlDoc.getElementsByTagName("to")[0];
t1.text=x.childNodes[0].nodeValue;

Sincerely, John


Are you sure the contents of your XML file is just this one line?

Tom Peter Reminder Don't forget me this weekend! 

If so, that could be your problem right there. Or if your tags are missing in the questions, that because you need to tell StackOverflow to format it as code by selecting it and pressing the code button (or Ctrl + K). Please edit your question, otherwise I cannot tell whether there is a problem with the statement you have used to parse the XML.

Another problem I see is in your ActionsScript:
You may not load the XML file and then parse it immediately after, because it doesn't happen sequentially (happens in a different thread). You need to use a URLLoader to load the XML, and add an event listener for the URLLoader's Event.COMPLETE event. In that method, do what you need to do with parsing the XML.


I am assuming you are using AS3 and not AS2

EDIT : Added code sample

In the main method where you start loading from the XML

var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, showNote);

Create a new method

function showNote(e:Event):void
{    
    var note:XML = new XML(e.target.data);
    var to:String = note.to[0].text();
    var from:String = note.from[0].text();
    var body:String = note.body[0].text();
    //t1.text = "To: " + to + "\nFrom: " + from + "\n\n" + body;
    t1.htmlText = "<p>To: " + to + "</p><p>From: " + from + "</p><p>" + body + "</p>";
}

Be sure to make sure that you have declared a text field on the stage with the instance name of t1, and to set its properties to multiline with wrap for this to work.

So basically, I think the problem with your original code was one of the following:

  1. You wanted a String, and to get that from and XML node, you need to use the text() method. There are other ways as well, but this is themost basic.
  2. The way you are traversing the XML tree using getElementsByTagName and childNodes may or may not be correct, but it is certainly easier to get wrong. AS3 provides a much more intuitive means to get the stuff from the XML, such as the one I have given in my example.
0

精彩评论

暂无评论...
验证码 换一张
取 消