这是一个如何检索一些数据的简单示例。这个例子很简单,没有使用 XPath 表达式。我建议你先了解它是如何工作的,然后再使用 XPath 表达式。在我看来,如果您无法理解解析器的工作原理,那么使用 XPath 表达式是没有用的。
NSString* path = [[NSBundle mainBundle] pathForResource:@"test2" ofType:@"xml"];
NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:path];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData
options:0 error:&error];
//NSLog(@"%@", doc.rootElement); // print the whole xml
NSArray *orderDataArray = [doc.rootElement elementsForName:@"OrderData"];
for (GDataXMLElement *orderDataElement in orderDataArray) {
if([orderDataElement childCount] > 0)
{
NSString *attributeForOrderDataElement = [(GDataXMLElement *) [orderDataElement attributeForName:@"HASH"] stringValue];
NSLog(@"attributeForOrderDataElement has value %@", attributeForOrderDataElement);
GDataXMLElement* idElement = (GDataXMLElement*)[[orderDataElement elementsForName:@"id"] objectAtIndex:0];
NSLog(@"id has value %@", idElement.stringValue);
GDataXMLElement* orderDetailElement = (GDataXMLElement*)[[orderDataElement elementsForName:@"orderDetail"] objectAtIndex:0];
GDataXMLElement* listElement = (GDataXMLElement*)[[orderDetailElement elementsForName:@"list"] objectAtIndex:0];
NSArray* orderDetailDataArray = [listElement elementsForName:@"OrderDetailData"];
int count = 0;
for (GDataXMLElement *orderDetailDataElement in orderDetailDataArray) {
NSString *attributeForOrderDetailDataElement = [(GDataXMLElement *) [orderDetailDataElement attributeForName:@"HASH"] stringValue];
NSLog(@"attributeForOrderDetailDataElement has value %@", attributeForOrderDetailDataElement);
count++;
}
NSLog(@"%d", count);
}
}
[doc release];
[xmlData release];
这是输出控制台:
attributeForOrderDataElement has value 208524692 <-- HASH value
id has value 97 <-- id value
attributeForOrderDetailDataElement has value 516790072 <-- HASH value
attributeForOrderDetailDataElement has value 11226247
attributeForOrderDetailDataElement has value 11226247
3 <-- the count
希望能帮助到你。
编辑
test2.xml 包含您的文件,但您可以将其作为字符串传递。您还可以将参数作为字符串传递,如下所示:
NSString* xmlString = @"<list>"
"<OrderData HASH=\"1408108039\"></OrderData>"
"<OrderData HASH=\"208524692\">"
"<id>97</id>"
"<customer>"
"<CustomerData HASH=\"2128670187\"></CustomerData>"
"</customer>"
"<billingAddress></billingAddress>"
"<deliveryAddress></deliveryAddress>"
"<orderDetail>"
"<list>"
"<OrderDetailData HASH=\"516790072\"></OrderDetailData>"
"<OrderDetailData HASH=\"11226247\"></OrderDetailData>"
"<OrderDetailData HASH=\"11226247\"></OrderDetailData>"
"</list>"
"</orderDetail>"
"<log/>"
"</OrderData>"
"<OrderData HASH=\"1502226778\"></OrderData>"
"</list>";
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithXMLString:xmlString options:0 error:&error];