XML parsing for iOS development and iosxml Parsing
XML parsing in iOS development 1. XML format
Structure: layered nested Tree Structure
<? Xml version = "1.0" encoding = "UTF-8"?>
1.0 indicates the XML file version, and UTF-8 indicates the encoding used by the internal text
<Root> indicates the root node.
<CityName> Beijing </CityName> is a node. CityName indicates the end name and Beijing node value.
<Item key = "1" value = "A"> </Item> key = "1" is the node attribute, key attribute name, and "1" attribute value.
2. How to use the open-source GData library to implement common XML parsing methods for XML Parsing
(1) unix-libxml2 C interface
(2) The XML parsing library provided by NSXMLParser UI is troublesome to use.
(3) GData development by google
2.1 Configuration
// (1) Add the Header file Search path // Header Search Paths->/usr/include/libxml2 // (2) add a binary library // Link library-> libxml2.dylib // (3) add compilation options to the source file //-fno-objc-arc // (4) add the header file // # import "GDataXMLNode. h"
2.2 Use of GData
// 1. load and parse the XML file NSString * path = [[NSBundle mainBundle] pathForResource: @ "xml.txt" ofType: nil]; NSData * data = [[NSData alloc] initWithContentsOfFile: path]; // GDataXMLDocument indicates the XML Document Object // initWithData is initialized using NSData, that is, parsing GDataXMLDocument * doc = [[GDataXMLDocument alloc] initWithData: data options: 0 error: nil]; // 2. obtain the path of the specified node XPath // CityName:/root/systemConfig/CityName NSArray * array = [doc nodesForXPath: @ "/root/systemConfig/CityName" error: nil]; // CityName GDataXMLElement * element = [array firstObject]; NSLog (@ "name = % @ value = % @", element. name, element. stringValue); // 3. get the attribute NSArray * items = [doc nodesForXPath: @ "/root/systemConfig/ComeChannel/Item" error: nil]; GDataXMLElement * item = [items firstObject]; // obtain attributes. The attributes are represented by GDataXMLElement for (GDataXMLElement * attr in item. attributes) {NSLog (@ "a-name = % @ avalue = % @", attr. name, attr. stringValue);} // 4. get all nodes with the specified name (regardless of location) // XPath Syntax: // Item NSArray * allItem = [doc nodesForXPath: @ "// Item" error: nil]; for (GDataXMLElement * e in allItem) {NSLog (@ "name = % @", e. name);} // 5. obtain the attributes of all specified names (regardless of the node) // XPath Syntax: // @ value NSArray * allValue = [doc nodesForXPath: @ "// @ value" error: nil]; for (GDataXMLElement * e in allValue) {NSLog (@ "value = % @", e. stringValue);} // 6. traverse XML files layer by layer // obtain the root node GDataXMLElement * root = doc. rootElement; // obtain the subnode // root. children // obtain the number of subnodes // root. childCount // obtain the child node with the specified name // root elementsForName: <# (NSString *) #>