使用Flash Builder中的datagrid将数据保存回xml文件

时间:2014-08-18 09:44:47

标签: xml flex flex-spark

我有一个xml文件,其中包含已在公司注册的员工详细信息。我使用本地服务器填充xml。我有一个登录页面,并有一个注册页面。我已成功将我的xml数据填充到数据网格中,无法通过文本输入字段更新或添加新员工。请帮助我完成在硬盘中更新我的xml文件所需的过程。

    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx"
           xmlns:registration="services.registration.*"
           creationComplete="employeeService.send()" currentState="login"
           minWidth.registration="955" minHeight.registration="600">

    <s:layout>
        <s:BasicLayout/>
    </s:layout>
    <fx:Style source="assgpart2.css"/>


    <s:states>
         <s:State name="registration"/>
         <s:State name="login"/>
         <s:State name="home"/>
    </s:states>


    <fx:Script>

    <![CDATA[
        import events.Task;
        import mx.controls.Alert;
        import mx.events.FlexEvent;
        import mx.events.ValidationResultEvent;
        import mx.messaging.messages.ErrorMessage;
        import mx.rpc.events.ResultEvent;
        import mx.utils.ObjectUtil;

        private var indexCounter:Number = 0;

        private function validateForm():void
        {
            var vreName:ValidationResultEvent= un.validate();
            var vrepass:ValidationResultEvent= ps.validate();
            var vrecnfpass:ValidationResultEvent= cp.validate();
            var vrefName:ValidationResultEvent= fn.validate();
            var vrelName:ValidationResultEvent= ln.validate();
            var vreemail:ValidationResultEvent= em.validate();
            var vredate:ValidationResultEvent= datevalid.validate();

            if( vreName.type == ValidationResultEvent.VALID &&
                vrepass.type == ValidationResultEvent.VALID &&
                vrecnfpass.type == ValidationResultEvent.VALID &&
                vrefName.type == ValidationResultEvent.VALID &&
                vrelName.type == ValidationResultEvent.VALID &&
                vreemail.type == ValidationResultEvent.VALID &&
                vredate.type == ValidationResultEvent.VALID )
            {
                if((male.selected== '0') && (female.selected == '0'))
                {
                    mx.controls.Alert.show("you forgot to enter your gender....!");
                }
                else
                {
                    mx.controls.Alert.show("thank you for registaring with us....!!!");
                }
            }

            else
            {
                mx.controls.Alert.show("enter valid details");
            }
        }



        private function validatelogin(event:MouseEvent):void
        {
        //  getemployeesResult.token = login.getemployees(urname.text, passwd.text);
        }

    ]]>
    </fx:Script>

    <fx:Declarations>
    <s:HTTPService id="employeeService"
                   url="C:\Users\rknikhil\Adobe Flash Builder 4.6\Assignment1\src\assests\registration.xml"
                   result="employeeService_resultHandler(event)" method.registration="post">

    </s:HTTPService>
    <mx:StringValidator id ="un"  source =" {uname}" property = "text" />
    <mx:StringValidator id ="ps"  source =" {pswd}" property = "text" />
    <mx:StringValidator id ="cp"  source =" {cnfpass}" property = "text" />
    <mx:StringValidator id ="fn"  source =" {fname}" property = "text" />
    <mx:StringValidator id ="ln"  source =" {lname}" property = "text" />
    <mx:StringValidator  source =" {email2}"
                         property = "text"
                         minLength.registration="8"
                         tooShortError.registration="min of 8 length" 
                         />


    <mx:EmailValidator id ="em" source= "{email2}" 
                       property="text" 
                       requiredFieldError.registration="have to contain ----@---.com" />


    <mx:DateValidator id="datevalid"
                      source = "{datev}" 
                      inputFormat.registration="MM-DD-YYYY" 
                      property = "text"
                      requiredFieldError.registration= "enter in MM-DD-YYYY format" />  


    <s:RadioButtonGroup id="gender"/>

    <s:CallResponder id="getemployeesResult"/>
    <registration:Registration id="registration"
                               fault="Alert.show(event.fault.faultString + '\n' + event.fault.faultDetail)"
                               showBusyCursor="true"/>
    <s:CallResponder id="getemployeesResult2"/>
    <s:CallResponder id="getemployeesResult3"/>

    <!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>




<s:Panel id="login" includeIn="login " x="0" y="0" width="100%" height="100%"
         backgroundAlpha="0.0" contentBackgroundAlpha="0.0" title="login"
         backgroundAlpha.login="400">

    <s:Label x="16" y="196" text="username"/>
    <s:TextInput id="urname" x="87" y="186"/>
    <s:Label x="12" y="239" text="password"/>
    <s:TextInput id= "passwd" x="87" y="238"/>
    <s:Button x="10" y="278" label="login" click="validatelogin(event)"/>
    <s:Button x="568" y="278" label="register" click ="currentState='registration'"/>

    <mx:DataGrid id="dataGrid" x="2" y="2"
                 creationComplete="dataGrid_creationCompleteHandler(event)"
                 dataProvider="{getemployeesResult.lastResult}" editable.login="true">
        <mx:columns>
            <mx:DataGridColumn dataField="username" headerText="username"/>
            <mx:DataGridColumn dataField="email" headerText="email"/>
            <mx:DataGridColumn dataField="firstname" headerText="firstname"/>
            <mx:DataGridColumn dataField="lastname" headerText="lastname"/>
            <mx:DataGridColumn dataField="dob" headerText="dob"/>
            <mx:DataGridColumn dataField="gender" headerText="gender"/>
        </mx:columns>
    </mx:DataGrid>


    <s:Label x="379" y="220" width="92" height="19"
             text="{employeeService.lastResult.employees.employee.username}"/>
</s:Panel>







    <s:VGroup includeIn="registration" y="15" width="50%" height="50%" horizontalCenter="221">

        <s:HGroup width="300" height="30">

            <s:FormItem label="username" required = "true">
                <s:TextInput id="uname" height="21" color="#D42222"
                             text="{getemployeesResult.lastResult[0].username}"/> 

            </s:FormItem>

        </s:HGroup>

        <s:HGroup width="300" height="30">
            <s:FormItem label="password" required = "true">
            <s:TextInput id="pswd" width="150" color="#D42222"
                         text="{getemployeesResult.lastResult[0].password}"/> 
            </s:FormItem>
        </s:HGroup>


        <s:HGroup width="300" height="30">
            <s:FormItem label="confirmpassword" required = "true" >
                <s:TextInput id="cnfpass" width="150" color="#D42222"
                             text="{getemployeesResult.lastResult[0].confirmpassword}"/>
            </s:FormItem>
        </s:HGroup>

        <s:HGroup width="300" height="30">
            <s:FormItem label="email" required = "true" >
                <s:TextInput id="email2" width="150" color="#D42222" text="{getemployeesResult.lastResult[0].email}" /> 
            </s:FormItem>
        </s:HGroup>

        <s:HGroup width="300" height="30">
            <s:FormItem label="first name" required = "true">
                <s:TextInput id="fname" width="150" color="#D42222"
                             text="{getemployeesResult.lastResult[0].firstname}"/> 
            </s:FormItem>
        </s:HGroup>


        <s:HGroup width="300" height="30">
            <s:FormItem label="last name" required = "true">
                <s:TextInput id="lname" width="150" color="#D42222"
                             text="{getemployeesResult.lastResult[0].lastname}"/> 
            </s:FormItem>
        </s:HGroup>



        <s:HGroup width="300" height="30">
            <s:FormItem label="date of birth" required = "true">
                <s:HGroup>
                    <s:TextInput id="datev" width="150" color="#D42222"
                                 text="{getemployeesResult.lastResult[0].dob}"/>
                </s:HGroup>
            </s:FormItem>
        </s:HGroup>

        <s:HGroup>
            <s:Label id= "gen" backgroundColor="#A6A1A1" chromeColor="#131212" color="#FCFAF8"
                     paddingBottom="5" paddingLeft="5" paddingRight="5" paddingTop="5"
                     text="gender"/>
            <s:RadioButton id="male" label="male" groupName="gender"/>
            <s:RadioButton id="female" label="female" groupName="gender" />

        </s:HGroup>
        <s:Button id="submit1" label="Submit" />
        <s:Button id="back" label="Back" click="currentState='login'"/>
    </s:VGroup>



    <s:Panel includeIn="home" x="4" y="2" width="100%" height="100%" fontFamily="Times New Roman"
         fontSize="20" fontWeight="bold" title="welcome to the home page">
    <s:BorderContainer x="0" y="0" width="100%" height="100%" fontFamily="Times New Roman"
                       fontSize="12">
        <s:Form includeIn="home" x="404" y="25" width="100%" height="100%">
            <s:FormItem label="name">
                <s:BorderContainer width="200" height="27">
                    <s:RichText width="100%" height="100%" color="#020202" fontSize="16"
                                horizontalCenter="0" paddingBottom="5" paddingLeft="5"
                                paddingRight="5" paddingTop="5" text="{urname.text} "
                                verticalCenter="0"
                                styleName.home="assgpart2.as"/>
                </s:BorderContainer>
            </s:FormItem>
            <s:FormItem label="comments">
                <s:BorderContainer width="200" height="97">
                    <s:RichEditableText left="0" top="0" width="100%" height="100%" text=""/>
                </s:BorderContainer>
            </s:FormItem>
            <s:Button label="confirm" cornerRadius="5"/>
        </s:Form>
        <s:Image includeIn="home" x="0" y="2" width="382" height="285" opaqueBackground="true"
                 smooth="true" source="images/Lighthouse.jpg"/>
    </s:BorderContainer>
    </s:Panel>
<mx:LinkButton x="70" y="250" label="forgot password ?"  focusColor="#FD0101"
               rollOverColor="#FCF8F8" textDecoration="underline"
               x.login="85" y.login="311"/>


</s:Application>

2 个答案:

答案 0 :(得分:0)

我看了你的代码&amp;但是,我无法找到能够/可以写入XML文件的任何内容,例如写,重写 - 更新或添加???我看到的是简单的读出XML文件!关于aktell

答案 1 :(得分:0)

好的,我已将我的应用程序复制了几年,我已经使用了几年,而且它在我的服务器上运行,因此它已经得到了很好的证明,并且完美无缺!但当然这完全取决于我自己的要求,这些只是读写基础知识。希望能帮助您对自己的应用程序进行排序! rgards aktell

我使用了TextInput组件!!!

            INIT ....
        import flash.filesystem.*;




<mx:Script>
    <![CDATA[

        import mx.rpc.events.FaultEvent;
        import mx.controls.Alert;

        import mx.rpc.events.ResultEvent;
        import mx.rpc.xml.SimpleXMLDecoder;

        import mx.rpc.http.HTTPService;

        private var myHTTP:HTTPService = new HTTPService();

        private function initConfigCall():void {

            myHTTP.url = "com/assets/data/.......? file.xml";

            myHTTP.send();
            myHTTP.resultFormat = "xml";
            myHTTP.addEventListener(ResultEvent.RESULT, resultHandler);
            myHTTP.addEventListener(FaultEvent.FAULT, faultHandler);    
        }

        private function resultHandler(evt:ResultEvent):void {

            var xmlStr:String = evt.result.toString();
            var xmlDoc:XMLDocument = new XMLDocument(xmlStr);
            var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
            var resultObj:Object = decoder.decodeXML(xmlDoc);

            // Removed [0] on single node !
            plnMsg.title = resultObj.application.configApp.appNewUpDate +''+  resultObj.application.configApp.appLastChanged;
            /* appLastChanged.text = resultObj.application.configApp.appLastChanged;
            appChangedSections.text = resultObj.application.configApp.appChangedSections; */

            myHTTP.disconnect();
            myHTTP = null;

            xmlStr = null;
            xmlDoc = null;
            decoder = null;
            resultObj = null;
        }
        private function faultHandler(event:mx.rpc.events.FaultEvent):void {

            var faultInfo:String="fault details: "+event.fault.faultDetail+"\n\n";
            faultInfo+="fault faultString: "+event.fault.faultString+"\n\n";
            mx.controls.Alert.show(faultInfo,"Fault Information");

            var eventInfo:String="event target: "+event.target+"\n\n";
            eventInfo+="event type: "+event.type+"\n\n";
            mx.controls.Alert.show(eventInfo,"Event Information");

            myHTTP.disconnect();
            myHTTP = null;

            myHTTP.removeEventListener(ResultEvent.RESULT, resultHandler);
            myHTTP.removeEventListener(FaultEvent.FAULT, faultHandler);
        }  
    ]]>
</mx:Script>






<!-- -->
<!-- *********************************************************************** -->
<!--    XML FILE READ OUT STREAM. -->
<!-- *********************************************************************** -->
<!-- -->
<mx:Script>
    <![CDATA[

        /* import flash.filesystem.FileStream;
        import flash.filesystem.FileMode;
        import flash.events.Event;
        import flash.filesystem.*; */

        private var myFileReadOut:File; 
        private var streamReadOut:FileStream = new FileStream(); 

        [Bindable] 
        private var xmlDataReadOut:XML;

        private function readOutXML():void {    

            myFileReadOut = File.desktopDirectory.resolvePath("Files/");
            myFileReadOut = myFileReadOut.resolvePath("dataONE.xml");

            if (myFileReadOut.exists) {

                streamReadOut.open(myFileReadOut, FileMode.READ);

                xmlDataReadOut = XML(streamReadOut.readUTFBytes(streamReadOut.bytesAvailable));


                Txt000_0.text = xmlDataReadOut.search000_0;
                PrefixTxt000_0.text = xmlDataReadOut.Prefix000_0;
                CountryTxt000_0.text = xmlDataReadOut.Country000_0;
                OnTxt000_0.htmlText = xmlDataReadOut.On000_0;

                streamReadOut.close();

                myFileReadOut = null;
                streamReadOut = null;

                xmlDataReadOut = null;
            }
        }
    ]]>
</mx:Script>








        private function saveStartData():void {

            xmlData = <urlGeneral/>;

            // 
            xmlData.search000_0 = Txt000_0.text;
            xmlData.Prefix000_0 = PrefixTxt000_0.text;
            xmlData.Country000_0 = CountryTxt000_0.text;
            xmlData.On000_0 = OnTxt000_0.text;

            var outputString:String = '<?xml version="1.0" encoding="utf-8"?>\n';

            outputString += xmlData.toXMLString();
            outputString = outputString.replace(/\n/g, File.lineEnding);

            stream = new FileStream();

            stream.open(myFile, FileMode.WRITE);
            stream.writeUTFBytes(outputString);

            stream.close();


            // Do NOT Use ! Second SAVE can give ERROR.
            /* myFile = null; */

            stream = null;

            xmlData = null;
            outputString = null;

            System.disposeXML(xmlData);
        }
    ]]>
</mx:Script>





<mx:Script>
    <![CDATA[

        /* import flash.filesystem.*; */

        private var myFile:File; 
        private var myFileONE:File; 

        private var stream:FileStream; 
        private var streamONE:FileStream;

        [Bindable] 
        private var xmlData:XML;    
        [Bindable] 
        private var xmlDataONE:XML;         

        public function AppInit():void {

            myFile = File.desktopDirectory.resolvePath("Files/");
            myFile = myFile.resolvePath("dataONE.xml");

            // Change over from - (desktopDirectory).
            myFileONE = File.applicationStorageDirectory.resolvePath("Files/DataFiles/");
            myFileONE = myFileONE.resolvePath("....?.xml");

            openXML();
            openXMLONE();
        }

        private function openXML():void {

            stream = new FileStream();

            if (myFile.exists) {

                stream.open(myFile, FileMode.READ); 

                xmlData = XML(stream.readUTFBytes(stream.bytesAvailable));

                stream.close();

                PhraseOneTxt.text = xmlData.Phrase001_0;
                PhraseTwoTxt.text = xmlData.Phrase002_0;
                PhraseThreeTxt.text = xmlData.Phrase003_0;
                PhraseFourTxt.text = xmlData.Phrase004_0;
                PhraseFiveTxt.text = xmlData.Phrase005_0;
                PhraseSixTxt.text = xmlData.Phrase006_0;
                PhraseSevenTxt.text = xmlData.Phrase007_0;
                PhraseEightTxt.text = xmlData.Phrase008_0;
                PhraseNineTxt.text = xmlData.Phrase009_0;

                // Do NOT Use ! Second SAVE can give ERROR.
                /* myFile = null; */

                stream = null; 

                xmlData = null;

                System.disposeXML(xmlData);
            }
        }






        private function lastRecordedRun():void {

            xmlDataONE = <urlGeneral/>;

            // Base Run 0.
            xmlDataONE.search000_0 = Txt000_0.text;
            xmlDataONE.Prefix000_0 = PrefixTxt000_0.text;
            xmlDataONE.Country000_0 = CountryTxt000_0.text;

            xmlDataONE.infoLastRun = lastRunTxt.text;
            xmlDataONE.saveStartDate = lastRunDateTime.text;

            xmlDataONE.Phrase001_0 = PhraseOneTxt.text;
            xmlDataONE.Phrase002_0 = PhraseTwoTxt.text;
            xmlDataONE.Phrase003_0 = PhraseThreeTxt.text;
            xmlDataONE.Phrase004_0 = PhraseFourTxt.text;
            xmlDataONE.Phrase005_0 = PhraseFiveTxt.text;
            xmlDataONE.Phrase006_0 = PhraseSixTxt.text;
            xmlDataONE.Phrase007_0 = PhraseSevenTxt.text;
            xmlDataONE.Phrase008_0 = PhraseEightTxt.text;
            xmlDataONE.Phrase009_0 = PhraseNineTxt.text;

            var outputStringONE:String = '<?xml version="1.0" encoding="utf-8"?>\n';

            outputStringONE += xmlDataONE.toXMLString();
            outputStringONE = outputStringONE.replace(/\n/g, File.lineEnding);

            streamONE = new FileStream();

            streamONE.open(myFileONE, FileMode.WRITE);
            streamONE.writeUTFBytes(outputStringONE);

            streamONE.close();


            // Do NOT Use ! SAVE can give ERROR.
            /* myFileONE = null; */

            streamONE = null;

            xmlDataONE = null;
            outputStringONE = null;

            System.disposeXML(xmlDataONE);


            startGCCycle();
        }