XML parsing and creation (GDataXML), xmlgdataxml

Source: Internet
Author: User

XML parsing and creation (GDataXML), xmlgdataxml

I. XML Parsing

For JSON parsing, iOS5 was previously supported by many open-source third-party classes (such as JSONKit), with one line of code. After iOS5, JSON can be parsed using native APIs, which is both convenient and efficient. However, the native API for XML parsing is not very friendly, and parsing is also troublesome. Fortunately, Google's GDataXML can be used for parsing. Please refer to my previous documents on how to integrate GDataXML into the project, using GDataXML for better parsing, the XML parsing principle can be understood as: the undressing mode. If you want to take a bath, take off your clothes from the outside to the inside, each piece of clothing can be considered as a GDataElement, and each GDataElement has its own value and attribute. Next we will parse the following XML data.

XML file data (file name Attribute. xml ):

<list>    <OrderData HASH="1408108039">od0</OrderData>    <OrderData HASH="208524692">        <id>97</id>        <customer>            <CustomerData HASH="2128670187">cd</CustomerData>        </customer>        <billingAddress>ba</billingAddress>        <deliveryAddress>da</deliveryAddress>        <orderDetail>            <list>                <OrderDetailData HASH="516790072">odd10</OrderDetailData>                <OrderDetailData HASH="11226247">odd11</OrderDetailData>                <OrderDetailData HASH="11226247">odd12</OrderDetailData>            </list>        </orderDetail>        <log>l</log>    </OrderData>    <OrderData HASH="1502226778">odd20</OrderData></list>

 

OC Parsing Code (all element values and attributes are printed using log ):

NSError * error = nil; NSString * filePath0 = [[NSBundle mainBundle] pathForResource: @ "Attribute" ofType: @ "xml"]; // obtain the Attribute in the project. xml file NSData * xmldata0 = [[NSData alloc] initWithContentsOfFile: filePath0]; GDataXMLDocument * doc0 = [[GDataXMLDocument alloc] initWithData: xmldata0 options: 0 error: & error]; GDataXMLElement * rootElement = doc0.rootElement; // obtain the node NSLog (@ "% @", rootElement); NSArray * messages = [rootElement elementsForName: @ "OrderData"]; if (messages. count> 0) {for (GDataXMLElement * element in messages) {// obtain the NSLog (@ "attrute: % @", [[element attributeForName: @ "HASH"] stringValue]); // obtain the HASH attribute value of OrderData. If there is no value, the obtained value is a combination of all sub-values (here: 97cdbadaodd10odd11odd12l) NSLog (@ "OrderData: % @", [element stringValue]); // obtain the id sub-element array NSArray * elementIDs = [element elementsForName: @ "id"]; if (elementIDs. count> 0) {for (GDataXMLElement * eID in elementIDs) {NSLog (@ "id: % d", [[eID stringValue] intValue]); // obtain the ID value} // obtain the NSArray * elementCustomers sub-element array of customer = [element elementsForName: @ "customer"]; if (elementCustomers. count> 0) {for (GDataXMLElement * eID in elementCustomers) {NSArray * customerDatas = [eID elementsForName: @ "mermerdata"]; if (customerDatas. count> 0) {for (GDataXMLElement * customerData in customerDatas) {NSLog (@ "customerData: % @", [customerData stringValue]); // obtain the value of customerData NSLog (@ "customerData-attrute: % @", [[customerData attributeForName: @ "HASH"] stringValue]); // obtain the HASH merdata HASH attribute value }}}// obtain the billingAddress subelement array NSArray * elementBillingAddresses = [element elementsForName: @ "billingAddress"]; if (elementBillingAddresses. count> 0) {for (GDataXMLElement * eID in elementBillingAddresses) {NSLog (@ "billingAddress: % @", [eID stringValue]); // obtain the billingAddress value} // obtain the deliveryAddress sub-element array NSArray * elementDeliveryAddressses = [element elementsForName: @ "deliveryAddress"]; if (elementDeliveryAddressses. count> 0) {for (GDataXMLElement * eID in elementDeliveryAddressses) {NSLog (@ "deliveryAddress: % @", [eID stringValue]); // get the deliveryAddress value} // obtain the orderDetail subelement array NSArray * elementOrderDetails = [element elementsForName: @ "orderDetail"]; if (elementOrderDetails. count> 0) {for (GDataXMLElement * eID in elementOrderDetails) {NSArray * lists = [eID elementsForName: @ "list"]; if (lists. count> 0) {for (GDataXMLElement * list in lists) {NSArray * OrderDetailDatas = [list elementsForName: @ "OrderDetailData"]; if (OrderDetailDatas. count> 0) {for (GDataXMLElement * OrderDetailData in OrderDetailDatas) {NSLog (@ "OrderDetailData-attribute: % @", [[OrderDetailData attributeForName: @ "HASH"] stringValue]); NSLog (@ "OrderDetailData: % @", [OrderDetailData stringValue]) ;}}}// obtain the log sub-element array NSArray * elementLogs = [element elementsForName: @ "log"]; if (elementLogs. count> 0) {for (GDataXMLElement * eID in elementLogs) {NSLog (@ "log: % @", [eID stringValue]); // obtain the log value }}}}

 

Is it clear that the parsing at this layer is not clear, so mom doesn't have to worry that I can't solve complicated XML. Here is a tip: You don't need to get the node like this when getting the node: GDataXMLElement * rootElement = doc. rootElement;

You can directly obtain the corresponding node through the path: NSArray * nodes = [doc nodesForXPath: @ "// Party/Player" error: & error];, in this way, the traversal layer is not required in a complicated XML file, and the desired layer is obtained directly.

 

Ii. XML Creation

XML creation and parsing is an inverse process, which can be understood as: dressing mode, getting up in winter, and creating clothes in the order of dressing, sweater, and coat. The same is true for creating an XML file. First, create and add a GDataXMLElement. Then, create an xml file for the following data:

<Party xmlns:name space="http://www.baidu.com" xmlns="http://www.google.com/hk" attribute="party's attribute">  <Player>    <Name>Butch</Name>    <Level>1</Level>    <Class>Fighter</Class>  </Player>  <Player>    <Name>Shadow</Name>    <Level>2</Level>    <Class>Rogue</Class>  </Player>  <Player>    <Name>Crak</Name>    <Level>3</Level>    <Class>Wizard</Class>  </Player></Party>

 

To simplify the code and logic, we first create two OC classes: Player and Party.

// Player. h file # import <Foundation/Foundation. h> typedef enum {RPGClassFighter = 0, RPGClassRogue, RPGClassWizard} RPGClass; @ interface Player: NSObject @ property (copy, nonatomic) NSString * name; @ property int level; @ property RPGClass rpgClass;-(id) initWithName :( NSString *) aName level :( int) aLevel rpgClass :( RPGClass) aRPGClass; @ end // Player. m file # import "Player. h "@ implementation Player-(id) initWithName :( NSString *) aName level :( int) aLevel rpgClass :( RPGClass) aRPGClass {if (self = [super init]) {_ name = aName; _ level = aLevel; _ rpgClass = aRPGClass;} return self ;}@ end // Party. h file # import <Foundation/Foundation. h> @ interface Party: NSObject @ property (strong, nonatomic) NSMutableArray * players; @ end // Party. m # import "Party. h "# import" Player. h "@ implementation Party-(instancetype) init {self = [super init]; if (self) {_ players = [[NSMutableArray alloc] init];} return self ;} @ end

 

Create XML method (three players are not provided here. Please write them directly)

+ (Void) saveParty :( Party *) aParty {GDataXMLElement * partyElement = [GDataXMLElement elementWithName: @ "Party"]; // Add attribute [partyElement addAttribute: [GDataXMLNode elementWithName: @ "attribute" stringValue: @ "party's attribute"]; // Add a namespace [partyElement addNamespace: [GDataXMLNode namespaceWithName: @ "name space" stringValue: @ "http://www.baidu.com"]; // Add the default namespace [partyElement addNamespace: [GDataXMLNode namespaceWithName: @ "" stringValue: @ "http://www.google.com/hk"]; for (Player * player in aParty. players) {GDataXMLElement * playerElement = [GDataXMLNode elementWithName: @ "Player"]; // create the element GDataXMLElement * nameElement = [GDataXMLNode elementWithName: @ "Name" stringValue: player. name]; GDataXMLElement * levelElement = [GDataXMLNode elementWithName: @ "Level" stringValue: [NSString stringWithFormat: @ "% d", player. level]; NSString * rpgClass = nil; if (player. rpgClass = RPGClassFighter) {rpgClass = @ "Fighter";} else if (player. rpgClass = RPGClassRogue) {rpgClass = @ "Rogue";} else if (player. rpgClass = inline) {rpgClass = @ "Wizard";} GDataXMLElement * rpgClassElement = [GDataXMLNode elementWithName: @ "Class" stringValue: rpgClass]; [playerElement addChild: nameElement]; // Add the name element [playerElement addChild: levelElement] to the player; // Add the level element [playerElement addChild: rpgClassElement] to the player; // Add the rpgClass element [partyElement addChild: playerElement]; // Add the player element to the party} GDataXMLDocument * doc = [[GDataXMLDocument alloc] initWithRootElement: partyElement]; NSData * xmlData = [doc XMLData]; NSString * filePath = [[NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: @ "makeXMLFile. xml "]; [xmlData writeToFile: filePath atomically: YES];}

 

Do you think it is not difficult to create XML after reading the code? (please correct me if there is anything unreasonable. Thank you !)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.