18 Replies Latest reply on Mar 21, 2007 2:03 PM by Queenalley

    How to load external XML into <DataGrid> ??

    hoverlink
      Hello ,everybody , I can't load external Xml like this format :

      ------------------------------------------------------------------------------------------ ----
      <list>

      <month name="Jan-04" revenue="400263" average="80052">
      <region name="APAC" revenue="46130"/>
      <region name="Europe" revenue="106976"/>
      <region name="Japan" revenue="79554"/>
      <region name="Latin America" revenue="39252"/>
      <region name="North America" revenue="128351"/>
      </month>
      <month name="Feb-04" revenue="379145" average="75829">
      <region name="APAC" revenue="70324"/>
      <region name="Europe" revenue="88912"/>
      <region name="Japan" revenue="69677"/>
      <region name="Latin America" revenue="59428"/>
      <region name="North America" revenue="90804"/>
      </month>
      </list>
      ------------------------------------------------------------------------------------------ ----

      I only can load with node format like this :

      ------------------------------------------------------------------------------------------ ----
      <order>
      <item>
      <menuName>burger</menuName>
      <price>3.95</price>
      </item>
      <item>
      <menuName>fries</menuName>
      <price>1.45</price>
      </item>
      </order>
      ------------------------------------------------------------------------------------------ ----

      Please tell me what am I going to do?
      Thanks!
        • 1. Re: How to load external XML into &lt;DataGrid&gt; ??
          peterent Level 2
          I don't see anything obviously wrong with your XML. What errors are you getting.
          • 2. Re: How to load external XML into &lt;DataGrid&gt; ??
            hoverlink Level 1
            quote:

            Originally posted by: peterent
            I don't see anything obviously wrong with your XML. What errors are you getting.


            Thanks and I means in Flex sample "Dashboard ", I don't know how dashboard ("RevenueTimeline.mxml") load "results.xml" file into DataGrid by HTTPService, and the ActionScript 3.0 looks a little complicate. Please give me a suggestion.
            • 3. Re: How to load external XML into &lt;DataGrid&gt; ??
              ntsiii Level 3
              What is your back-end platform?
              Tracy
              • 4. Re: How to load external XML into &lt;DataGrid&gt; ??
                Xygar
                Here's a quick example, assuming you were to get your XML from an HTTPService:

                --------------------------------------------------

                <mx:HTTPService id="dataRequest" resultFormat="e4x"></mx:HTTPService>

                <mx:XMLListCollection id="myData" source="{dataRequest.lastResult.month}" CollectionChange="dataChanged(event);">
                </mx:XMLListCollection>

                <mx:DataGrid id="dataGrid" width="100%" dataProvider="{myData}" editable="true"
                itemEditEnd="editItem(event);" variableRowHeight="true">
                <mx:columns>
                <mx:DataGridColumn dataField="region" headerText="Region" wordWrap="true"></mx:DataGridColumn>
                </mx:columns>
                </mx:DataGrid>

                -------------------------------------

                Of course, what I did with your data doesn't make a lot of sense. I'm not sure how you want to represent the information, but if you want to display hierarchical data, you might want to use a tree. Either that or you'll need to build your own component. Of course, I'm very new to this stuff, so there might be other tricks you can work with the datagrid.

                BTW, I have some extra things in there. I declared an XMLListCollection object as my data source so that I could trap change events (provided your going to add, remove, and edit data). Also, the datagrid is set to editable and has an event to detect when a cell has finished its edit (see docs). Also, you have to set the variableRowHeight property if you want to wordWrap your cells.

                I hope this helps. I'm currently in the process of using a DataGrid for an application, so this stuff is at the top of my priority list right now. ;)

                P.S. Is there a [code] tag for this forum so that I can format my code examples properly? Thanks.
                • 5. Re: How to load external XML into &lt;DataGrid&gt; ??
                  hoverlink Level 1
                  Thank you for your example and ...
                  how to define functions of "dataChanged" and "editItem" ?
                  • 6. Re: How to load external XML into &lt;DataGrid&gt; ??
                    hoverlink Level 1
                    quote:

                    Originally posted by: ntsiii
                    What is your back-end platform?
                    Tracy


                    .net , only can transfer data indirectly by Xml or WSDL files...?
                    thanks.
                    • 7. Re: How to load external XML into &lt;DataGrid&gt; ??
                      Xygar Level 1
                      Oh, I left out the fact that you need to set a URL and call the send() method of the HTTPService. ;)

                      As for examples of those functions, here ya go:

                      private function dataChanged(event:CollectionEvent):void {
                      //handle the change of data based on the kind of change
                      switch ( event.kind ) {
                      case CollectionEventKind.ADD :
                      //Indicates that the collection added an item or items.
                      break;
                      case CollectionEventKind.REMOVE :
                      //Indicates that the collection removed an item or items.
                      break;
                      case CollectionEventKind.UPDATE :
                      //Indicates that one or more items were updated within the collection.
                      //The affected item(s) or their associated ObjectChangeEvent objects
                      //are stored in the items property.
                      break;
                      case CollectionEventKind.MOVE :
                      //Indicates that the item has moved from the position identified by
                      //the CollectionEvent oldLocation property to the position identified by the location property.
                      break;
                      case CollectionEventKind.REFRESH :
                      //Indicates that the collection applied a sort, a filter, or both.
                      break;
                      case CollectionEventKind.REPLACE :
                      //Indicates that the item at the position identified by the
                      //CollectionEvent location property has been replaced.
                      break;
                      case CollectionEventKind.RESET :
                      //Indicates that the collection has changed so drastically that a
                      //reset is required.
                      break;
                      }
                      }

                      Check out the CollectionEvent and CollectionEventKind classes in the Language reference for other properties you can mess with.

                      As for itemEditEnd on the DataGrid, take a look at the DataGrid in the Language Reference document and you'll find what event class it expects, as well as additional events that are useful.
                      • 8. Re: How to load external XML into &lt;DataGrid&gt; ??
                        ntsiii Level 3
                        Xygar, regretfully, there is no way to add formatted to this forum at this time. I hope for this to change before too long.
                        • 9. Re: How to load external XML into &lt;DataGrid&gt; ??
                          ntsiii Level 3
                          hoverlink, Xygars example using HTTPservice is the best way with .net. Us an aspx page, set <%Response.ContentType = "text/xml", and just response.write xml text back to flex.

                          One piece of advice: Binding directly to lastResult is very hard to debug. I suggest using an event Hndler function called by the result event of the HTTPService. Also, you can bind directly to e4x XML. You do not have to usr an XMLListCollection.

                          Tracy
                          • 10. Re: How to load external XML into &lt;DataGrid&gt; ??
                            hoverlink Level 1
                            Xygar , I don't need edit and data change right now, thanks.

                            ntsiii, HTTPservice is very useful, thanks.
                            And I use e4x XML class , but "results.xml" can't be loaded when I add e4x function and sub-tags(<mx:columns>,<<mx:DataGridColumn>) in this mxml :
                            -------------------------------------------------------------------------
                            <mx:XML id="list" source="results.xml"></mx:XML>

                            <mx:Script>
                            <![CDATA[
                            import mx.controls.dataGridClasses.DataGridColumn;
                            import net.digitalprimates.utils.E4XParser;

                            protected function displayXMLData( row:Object, column:DataGridColumn ):String {
                            return E4XParser.evaluate( row, column.dataField );
                            }
                            ]]>
                            </mx:Script>

                            <mx:DataGrid dataProvider="{list.month}" width="450">
                            <mx:columns>
                            <mx:DataGridColumn headerText="month" dataField="month.@name" labelFunction="displayXMLData"/>
                            <mx:DataGridColumn headerText="Total Revenue" dataField="month.@revenue" labelFunction="displayXMLData"/>
                            <mx:DataGridColumn headerText="Average" dataField="month.@average" labelFunction="displayXMLData"/>
                            </mx:columns>
                            </mx:DataGrid>
                            -------------------------------------------------------------------------

                            Please tell me how to fix it , thanks.
                            • 11. Re: How to load external XML into &lt;DataGrid&gt; ??
                              Xygar Level 1
                              quote:

                              Originally posted by: ntsiii
                              hoverlink, Xygars example using HTTPservice is the best way with .net. Us an aspx page, set <%Response.ContentType = "text/xml", and just response.write xml text back to flex.

                              One piece of advice: Binding directly to lastResult is very hard to debug. I suggest using an event Hndler function called by the result event of the HTTPService. Also, you can bind directly to e4x XML. You do not have to usr an XMLListCollection.

                              Tracy


                              I'm sure you could just tie events to the XMLListCollection automatically created when you pass an XMLList as a provider. I like the <mx:/> tag format, which allowed me to set events there to listen for data changes.

                              Working with the result, instead of lastResult, is probably a good idea. Also, XMLListCollection doesn't always act the same as ArrayCollection does when report change events on a DataGrid. I found that ArrayCollection handled things a little more like I expected it too (XMLListCollection sent too many events). So, I used results as XML to create my ArrayCollection.

                              • 12. Re: How to load external XML into &lt;DataGrid&gt; ??
                                ntsiii Level 3
                                It doesn't work because you do not have a good reference to your data.

                                This won't work: source="results.xml" Do you understand why? There are two reasons.

                                And why are you tring to use "E4XParser"?

                                But skip the tag completely. Declare an instance (global) variable to hold the data:
                                [Bindable]private var _xmlResult:XML;
                                declare a result handler in the HTTPService tag:
                                <mx:HTTPService id="dataRequest" result="onResult(event)"

                                and the handler:
                                private function onResult(oEvent:ResultEvent):void {
                                _xmlResult = XML(oEvent.result);
                                trace(_xmlResult.toXMLString()); //so you can see your data is there


                                When you can see your data, post back and I will help you with the labelFunction.

                                Tracy


                                • 13. Re: How to load external XML into &lt;DataGrid&gt; ??
                                  hoverlink Level 1
                                  Hi ntsiii , I use HTTPService can load data from xml, thanks.

                                  There got 3 questions :
                                  1. I can not load xml tag attributes by @name, but it can load by dataField="name", why ?
                                  2. How to use the labelFunction ?
                                  3. The trace() can not show output in my flex 2.0 builder , why ? it's not easy use like Flash 8 professional .

                                  Thank you !
                                  -----------------------------------------------------------------
                                  <?xml version="1.0" encoding="utf-8"?>
                                  <mx:Application xmlns:mx=" http://www.adobe.com/2006/mxml" layout="vertical"
                                  initialize="myService.send()">

                                  <mx:Script>
                                  <![CDATA[
                                  import mx.collections.ArrayCollection;
                                  import mx.rpc.events.ResultEvent;

                                  [Bindable] private var myData:ArrayCollection;

                                  private function resultHandler(event:ResultEvent):void {
                                  myData = event.result.list.month;
                                  trace(myData);//can't see in output }
                                  ]]>
                                  </mx:Script>

                                  <mx:HTTPService id="myService"
                                  url="results.xml"
                                  result="resultHandler(event)"/>

                                  <mx:DataGrid width="100%" height="100%" dataProvider="{myData}">
                                  <mx:columns>
                                  <mx:DataGridColumn headerText="Month" dataField="name"></mx:DataGridColumn>
                                  <mx:DataGridColumn headerText="test2" dataField="revenue"></mx:DataGridColumn>
                                  <mx:DataGridColumn headerText="test3" dataField="average"></mx:DataGridColumn>
                                  </mx:columns>
                                  </mx:DataGrid>
                                  </mx:Application>
                                  -----------------------------------------------------------
                                  • 14. Re: How to load external XML into &lt;DataGrid&gt; ??
                                    ntsiii Level 3
                                    1. HTTPService defaults to returning Obect. Set resultFormat="e4x"
                                    2. Here are some examples, using XML. Note, a different function for each column works but you can also ue the "columns" argument to make one function work for multiple columns.
                                    3. trace() should just work in FB. I use it all the time. Are you sure you have the debug player? http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=tn_15507

                                    Tracy
                                    • 15. Re: How to load external XML into &lt;DataGrid&gt; ??
                                      hoverlink Level 1
                                      Thank you Tracy. I have the debug player ,but I can see the trace output info only source file error.
                                      • 16. How to load external XML into &lt;DataGrid&gt; ??
                                        Queenalley
                                        I'm stuck on this as well. I've read through the above samples and postings and am now feeling really retarded. I thought throwing the contents of a simple XML doc into a DataGrid would be easy, but I've been trying all morning and no love. Any help is appreciated.

                                        Here the XML --> guides.xml
                                        ________________________________________________________________________________
                                        <?xml version="1.0" encoding="UTF-8">
                                        <GuideList title="Current Guides">
                                        <GuideItem>
                                        <GuideName>11699240</GuideName>
                                        <DisplayName>Supercharged Branding Program</DisplayName>
                                        <LinkText>View Downloadable Guide</LinkText>
                                        <Franchise>Film/TV</Franchise>
                                        <Property>Cars</Property>
                                        </GuideItem>
                                        <GuideItem>
                                        <GuideName>11721503</GuideName>
                                        <DisplayName> Packaging & Retail Signage</DisplayName>
                                        <LinkText>View Downloadable Guide</LinkText>
                                        <Franchise>Film/TV</Franchise>
                                        <Property>None</Property>
                                        </GuideItem>
                                        etc....
                                        _____________________________________________________________________________

                                        Here's the flex --> GuideListDisplay.mxml
                                        _____________________________________________________________________________
                                        <?xml version="1.0" encoding="utf-8"?>
                                        <mx:Application xmlns:mx=" http://www.adobe.com/2006/mxml" layout="absolute" initialize="guidelist.send()">
                                        <mx:Script>
                                        <![CDATA[
                                        import mx.collections.ArrayCollection;
                                        import mx.rpc.events.ResultEvent;

                                        [Bindable] private var myData:ArrayCollection;

                                        private function resultHandler(event:ResultEvent):void {
                                        myData = event.result.GuideList.GuideItem;
                                        }
                                        ]]>
                                        </mx:Script>

                                        <mx:HTTPService id="guidelist" url="assets/guides.xml" result="resultHandler(event)"/>
                                        <mx:Panel title="{myData.GuideList.title}"> // 1119
                                        <mx:DataGrid x="29" y="36" id="Guides" dataProvider="{myData.lastresult.GuideList.GuideItem}"> // 1119
                                        <mx:columns>
                                        <mx:DataGridColumn headerText="Guide Number" dataField="GuideName"/>
                                        <mx:DataGridColumn headerText="Guide Name" dataField="DisplayName"/>
                                        <mx:DataGridColumn headerText="DisplayText" dataField="LinkText"/>
                                        </mx:columns>
                                        </mx:DataGrid>
                                        </mx:Panel>
                                        </mx:Application>
                                        ____________________________________________________________________________


                                        The lines throw with // 1119 throw a problem notice - 1119: Access of possibly undefined property GuideList through a reference with static type mx.collections:ArrayCollection. GuideListDisplay.mxml Lessons line 17 March 21, 2007 12:53:45 PM 215

                                        Please help before hari kari looks like a good option.
                                        Thanks!
                                        • 17. Re: How to load external XML into &lt;DataGrid&gt; ??
                                          EliteScientist
                                          change:
                                          dataProvider="{myData.lastresult.GuideList.GuideItem}"

                                          to:
                                          dataProvider="{myData}">
                                          • 18. Re: How to load external XML into &lt;DataGrid&gt; ??
                                            Queenalley Level 1
                                            Thanks BaTMaNX (is that a flying tail-less cat?).

                                            It was that and I was missing the trailing ? in the first line of my XML doc. Now it works fine.

                                            A thousand thanks...