Use of task to prepare a XmlDocument from a file with WinRT library functions.
-
mardi 10 juillet 2012 22:28
I was wondering if there is a better way to write a function that reads an XML file and turns it into a XmlDocument object, and then executes a user specified function on that XmlDocument. Not feeling too expert, I did come up with one solution, but would like an expert opinion on that solution, and also if there is a better way?
void FileIo::getXML( std::function< void ( Windows::Data::Xml::Dom::XmlDocument ^ passedDoc ) > myXmlDocHandler ) { using namespace Windows::Storage; using namespace Windows::Storage::Pickers; using namespace Windows::Data::Xml::Dom; using namespace concurrency; auto picker= ref new FileOpenPicker(); picker->FileTypeFilter->Append(".xml"); // Required task< StorageFile^ > getFileTask ( picker->PickSingleFileAsync() ); getFileTask.then([ myXmlDocHandler ]( StorageFile^ xmlFile ) { if ( xmlFile != nullptr) { auto doc= ref new XmlDocument(); task< XmlDocument ^ > getDocTask ( doc->LoadFromFileAsync( xmlFile ) ); getDocTask.then( [ myXmlDocHandler ] ( XmlDocument^ doc ) { myXmlDocHandler( doc ); }); } }); } //-------------------------------------- // Calling mechanism auto lambda = []( Windows::Data::Xml::Dom::XmlDocument ^ xmlDoc ) { // Now go process the XML file as you like Platform::String ^ nodeName= xmlDoc->NodeName; }; FileIo::getXML( lambda );
The full context is at:
Toutes les réponses
-
vendredi 10 août 2012 18:25
Hi, Andrew,
The code you pasted looks correct to me. For Yashpal_S 's question on that ref thread, there is an alternative api interface which returns a task of XmlDocument^ instread of asking user passing in an callback function.
The Pseudocode could be something like this:
concurrency::task<Windows::Data::Xml::Dom::XmlDocument> FileIo::getXML() { using namespace Windows::Storage; using namespace Windows::Storage::Pickers; using namespace Windows::Data::Xml::Dom; using namespace concurrency; auto picker= ref new FileOpenPicker(); picker->FileTypeFilter->Append(".xml"); // Required return create_task(picker->PickSingleFileAsync()).then([]( StorageFile^ xmlFile ) { if ( xmlFile == nullptr) cancel_current_task(); // abort current task and its continuations auto doc= ref new XmlDocument(); return doc->LoadFromFileAsync( xmlFile ); }) } // -------------------call it FileIo::getXML().then([](Windows::Data::Xml::Dom::XmlDocument doc) { // do whatever you want. });Hong
- Modifié Hong Hong - vendredi 10 août 2012 18:27
- Modifié Hong Hong - vendredi 10 août 2012 18:28
- Modifié Hong Hong - vendredi 10 août 2012 18:29

