转载自:
http://www.raywenderlich.com/725/how-to-read-and-write-xml-documents-with-gdataxml
In my recent post onHow
To Choose the Best XML Parser for Your iPhone Project, Saliom from the comments section suggested writing a post on how to use an XML library to read and write XML documents, create your own objects based on the documents, and perform XPath queries.
This tutorial will show you how to do exactly that! We’ll create a project that reads a simple XML document that contains a list of RPG party members, and construct our own objects based on the XML. We’ll then add a new player to the party, and save it back
out to disk again.
This tutorial uses GDataXML, Google’s XML processing library. I chose GDataXML since it performs well for DOM parsers, supports both reading and writing, and is so easy to integrate. However, if you are using a different DOM parser, it should be almost exactly
the same as this but just slightly different API calls.
Special thanks to Saliom for suggesting writing this tutorial!
Our XML Document
We’re going to work with a simple XML document in this tutorial that looks like the following:
As I mentioned, this list represents a list of characters you might have in a RPG dungeon crawl game. I wanted to keep the document pretty small to make the tutorial easy to follow, but still show you some interesting things such as using different datatypes
and having lists of objects.
Ok, so let’s get started on our project to read and write this thing!
Integrating GDataXML
You can integrate GDataXML into a new project with a few easy steps:
-
Choose Project\New Project, and choose View-based Application, and name the project XMLTest.
-
Download thegdata-objective-c
client library.
-
Unzip the file, navigate to Source\XMLSupport, and drag the two files GDataXMLNode.h and GDataXMLNode.m into your project.
-
In XCode, click Project\Edit Project Settings and make sure “All Configurations” are checked.
-
Find the Search Paths\Header Search Paths setting and add /usr/include/libxml2 to the list.
-
Finally, find the Linking\Other Linker Flags section and add -lxml2 to the list.
-
Test out that everything is working by adding the following to the top of XMLTestAppDelegate.h:
If your app compiles and runs GDataXML is integrated successfully!
Creating Model Classses
Next, let’s create a set of model classes that we want to represent our party of XML characters in our game. Basically, we want to make a set of objects that represent how we wish to work with our characters in our game.
First, let’s create our Player class. Click on File\New File, select Cocoa Touch Class\Objective-C class, choose Subclass of NSObject, and click Next. Name the file Player.m and verify that “Also create Player.h” is checked.
Then replace Player.h with the following:
And replace Player.m with the following:
Again, all of this is straight Objective-C, nothing really to do with XML at this point. However, I’m still including it for completeness sake.
Follow the same steps as above to create a new subclass of NSObject named Party. Replace Party.h with the following:
And Party.m with the following:
Ok, so far so good! Now let’s get to parsing our XML file and creating instances of these objects based on the XML.
Parsing the XML with GDataXML
Let’s get together some code quickly to use GDataXML to read the XML document and create a DOM tree in memory.
First,download
Party.xmland add it to your project.
Next, we’re going to create a new class to hold all of our parsing code. Add a new subclass of NSObject to your project named PartyParser.
Replace PartyParser.h with the following:
And then replace PartyParser.m with the following:
Ok, finally some semi-interesting code here. First we create a static method called dataFilePath that returns the path to the Party.xml that we included in our project (and hence becomes part of our application’s bundle). Note that we have a boolean that indicates
whether we want the path of the file for loading or saving – this isn’t used right now, but will be later.
Next, we create another static method called loadParty. This loads the raw bytes for the file off the disk with NSMutableData’s initWithContentsOfFile method, and then passes the data to GDataXML’s parser with the GDataXMLDocument initWithData method.
If GDataXML has an error parsing the file (such as a missing close tag), it will return nil and return an NSError with more information. For this tutorial, we’ll just return nil if this occurs.
However, if we receive a success, we just print out a description of the root element of the document (which should be thetag in our case).
Ok, let’s put this to use. Modify your XMLTestAppDelegate.h so it looks like the following:
Note all we did here was declare a Party member variable.
Then modify your XMLTestAppDelegate.m so it looks like the following:
Here we just add some include files and call the static method to load the party in our applicationDidFinishLaunching, and do some cleanup in our dealloc method.
Ok let’s see if it works so far! Compile and run your application, and if you go to Run\Console and scroll to the bottom, you should see something like the following print out:
Converting the XML to our Model Objects
Ok now that we see that it’s working so far, let’s continue the code to walk through the DOM tree and create instances of our model objects as we go.
The replace the code in the loadParty method starting with replacing the NSLog statement with the following:
This is the real meat of our work. We use the elementsForName method on our root element to get all of the elements named “Player” underneath the root “Party” element.
Then, for each “Player” element we look to see what “Name” elements are underneath that. Our code only deals with one name, so we just take the first if there is more than one.
We do similar processing for “Level” and “Class”, but for level we convert the string into an int, and for class we convert the string into an enumeration.
If anything fails, we just skip that Player. Otherwise, we construct a Player model object with the values we read from the XML, and add it to our Party model object, and return that!
So let’s write some code to see if it works. Add the following to XMLTestAppDelegate.m in applicationDidFinishLaunching, after the call to loadParty:
Compile and run your project, and if all works well you should see the following in the console output:
Querying with XPath
XPath is a simple syntax you can use to identify portions of an XML document. The easiest way to get a handle on it is by seeing a few examples.
For example, the following XPath expression would identify all of the Player elements in our document:
And the following would just identify the first Player element in our document:
And finally, the following would identify the player with the name of Shadow:
Let’s see how we could use XPath by slightly modifying our loadParty method. Replace the line that loads the party members as the following:
If you run the code, you’ll see the exact same results. So there isn’t an advantage of using XPath in this case, since we are interested in reading the entire XML document and constructing a model in memory.
However, you can imagine that this could be pretty useful if we had a big complicated XML document and we wanted to quickly dig down to find a particular element, without having to look through the children of node A, then the children of node B, and so on
until we find it.
If you are interested in learning more about XPath, check out a nicetutorial
from W2Schools. Also, I’ve found thisonline
XPath expression testbedquite handy when trying to construct XPath expressions.
Saving Back to XML
So far we’ve only done half of the picture: reading data from an XML document. What if we want to add a new player to our party and then save the new document back to disk?
Well, the first thing we need to do is determine where we are going to save the XML document. So far we’ve been loading the XML document from our application’s bundle. We can’t save to the bundle, however, because it is read-only. But we can save to the application’s
document directory, so let’s do that.
Modify your dataFilePath method in PartyParser.m to read as follows:
Note that when we’re loading the XML, we want to load from the file in the documents directory if it exists, but otherwise fall back to reading the XML file that ships with the app, like we’ve been doing so far.
Now, let’s write a method to construct our XML document from our data model and save it out to disk. Add a new methdo to PartyParser.m as follows:
As you can see, GDataXML makes it quite easy and straightforward to construct our XML document. You simply create elements with elementWithName: or elementWithName:stringValue, connect them to each other with addChild, and then create a GDataXMLDocument specifying
the root element. In the end, you get an NSData that you can easily save to disk.
Next declare your new method in PartyParser.h:
Then inside the party != nil check in applicationDidFinishLaunching, go ahead and add a new party member to our list:
And finally let’s save out the updated party list in applicationWillTerminate:
Compile and run your project, and after the app loads go ahead and exit. The app should print out to the console where it saves your XML. It will look something like this:
Go ahead and find that folder with Finder and open up the XML, and if all goes well you should see your new party member in the XML:
Then run the app again, open up your console log, and see if you can find where Waldo is! :]
And That’s A Wrap!
Here is asample
projectwith all of the code that we’ve developed in the tutorial so far. Note that the app doesn’t show anything in the GUI as that isn’t important for this tutorial – it just shows a few output lines in the console.
By the way – before you use XML in your projects, you should take a second to consider why you want to use XML in the first place and if that is the best choice. In this example, if all we were using XML for was loading and saving characters for this particular
app, XML would probably be overkill, and it would be better to use another serialization format such as property lists, NSCoding, or even Core Data.
However, XML really starts to shine when you start having multiple applications use the same data. If we had a Mac application that generated a list of characters and we wanted our iPhone app to be able to read and modify that list, that’s when it becomes to
be particularly useful. This is because XML is a standard format for exchanging data that is quite easy to work with, as you’ve seen.
So any plans to use XML reading and writing in your apps? What are you using it for?
分享到:
相关推荐
This text makes a great supplement and provides a systematic approach for teaching undergraduate and graduate students how to read, understand, think about, and do proofs. The approach is to ...
How to write and publish a scientific paper ContentsChapter 1 What Is Scientific Writing? Chapter 2 Origins of Scientific Writing Chapter 3 What Is a Scientific Paper? Chapter 4 How to Prepare the ...
How to Write and Publish a Scientific Paper 非影印版,可以复制粘贴
The middle section of the book deals with client-side XML applications and shows how to display and transform XML documents with CSS and XSLT. This section also explores how the current web browsers ...
Read XML files with XMLDocuMent and XDocument Write XML with XMLDocument, XDocument, and XMLWriter Modifiy your XML with XML Document and XDocument Who This Book Is For Experienced Windows application...
How to Write & Publish a Scientific Paper,教你怎样发布期刊,硕博士极力推荐
How to Read a Book, originally published in 1940, has become a rare phenomenon, a living classic. It is the best and most successful guide to reading comprehension for the general reader. And now it ...
The growth of XML content management ...Beginning XSLT and XPath: Transforming XML Documents and Data is the essential guide you need to thoroughly understand the important XSLT processing model.
patterns found in XML documents. It relies almost entirely on XPath query patterns for defining rules and checks.Schematron validation rules allow the author to specify a helpful error message which ...
Extensible Stylesheet Language Transformations (XSLT) is a language for transforming XML documents and data from one format to another. Answering the demand for an introductory book on XSLT processing...
From proposal to examination, producing a dissertation or thesis is a challenge. Grounded in decades ... How to Write a Better Thesis presents a cohesive approach to research that will help you succeed.
How to read scientific paper原文 大佬详细讲解了如何读论文,主要分为三遍,每次都要更加深入,最后一遍更是直接到了复现的程度,是工科生读论文的非常好的指南。
How to Write a Good Scientific Paper by Chris A. Mack is a valuable resource for all students and faculty in science and engineering. SPIE is pleased to make it available here at no charge as a PDF ...
A special feature of this edition is a new appendix on NoSQL and relational theory.Could you write an SQL query to find employees who have worked at least once in every programming department in the ...
This book provides practical, proven techniques for making writing for ... All levels of business and technical personnel will find this easy-to-read guide invaluable and immediately useful every day.
本文的完整版本最初出现在作者的个人博客(www.violentmetaphors.com)上。 她非常感谢José Bonner教授(印第安纳大学)和Bill Saxton教授(加州大学圣克鲁兹分校)教她如何使用这种方法阅读科学论文。
More use of personal pronouns such as the first person(pl.) and third person 1. We suggest here that seedling respond… (author) 2. We can make one prediction on the basis of…(author and reader) 3. ...
这是一个讲解Unity3D中运用陀螺仪的分析步骤,及注意事项 里面有具体的讲解,特别是文档最下方有个例子链接,结合例子能够更好的了解unity3d调用Gyroscope在移动端的运用
book, you’ll learn how to write documents in XML and how to use style sheets to convert those documents into HTML so legacy browsers can read them. You’ll alsolearn how to use document type ...
displaying spatial-temporal displays with Google Earth, and generating code from descriptions of data structures to read and write data. These topics demonstrate the rich possibilities and ...