XML parsing code for iOS development and iosxml Parsing
XML parsing code for iOS development
// 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 *) #>}
: