我有以下xml,我需要使用TouchXML进行解析。
<?xml version="1.0"?>
<categories>
<category0>
<title>Alcoholic Drinks</title>
<description>Buy beers, wines, sprits and champagne from the top online alocholic drink stores.
Whatever your tipple you are sure to find a drinks supplier from our top shops below:
</description>
<status>1</status>
<popularStatus></popularStatus>
<order></order>
<link>alcoholic-drinks</link>
<id>1</id>
</category0>
<category1>
<title>Art and Collectibles</title>
<description>Are you looking to buy contemporary or fine art, or do you prefer to make your own artwork?&#

Whether type of artwork or craft materials you are looking for, you are certain to find one of the shops below more than helpful:
</description>
<status>1</status>
<popularStatus></popularStatus>
<order></order>
<link>art-and-collectibles</link>
<id>2</id>
</category1>
<category2>
<title>Auctions</title>
<description>Are you looking for the UK's biggest and best Auction Sites?
The team at safebuyer.co.uk have scoured the web to find the UK's favourite auctions, so why wait, start your bidding now!
</description>
...
...
...
我正在考虑从根节点创建两个循环以获取标题和链接,但是想知道如何去做。请有人帮忙。
答案 0 :(得分:1)
如果您可以更改XML文件并使所有类别标记相同。你可以把所有...而不是......和....
所以这很容易解析。您只需要创建类别类,如果您有正确的xml解析代码,则所有标记都将自动解析。
答案 1 :(得分:1)
CXMLNode *node;
for(i=0; i<10 ; i++){
NSString *xpath = [NSString stringWithFormat:@"//category%d/title", i];
NSArray *title = [[node nodesForXPath:xpath] stringValue];
}
使用上面的代码..
答案 2 :(得分:0)
CXMLElement *element;
NSArray *titleItems = [[NSArray alloc] initWithArray:[element nodesForXPath:@"//category" error:nil]];
for(CXMLElement *item in titleItems){
NSString *title = [[item selectSingleNode:@"title"] stringValue];
}
注意:类别节点应重复.....
答案 3 :(得分:0)
下面的代码为您提供了一个字典,其中键是标题,数据是链接。当然,如果您的XML文档“很大”,这不是最好的方法。
CXMLDocument *doc = [[[CXMLDocument alloc] initWithXMLString:theXML options:0 error:nil] autorelease];
NSArray *categories = nil;
NSMutableDictionary* results = nil;
categories = [doc nodesForXPath:@"/categories/*[starts-with(name(), 'category')]" error:nil];
if (categories != nil && [categories count] > 0)
{
results = [NSMutableDictionary dictionaryWithCapacity:[categories count]];
for (CXMLElement *category in categories)
{
NSArray* titles = [category elementsForName:@"title"];
if ([titles count] >0)
{
NSArray* links = [category elementsForName:@"link"];
[result setObject:([links count]>0?[[links objectAtIndex:0] stringValue]:nil;
forKey:[[titles objectAtIndex:0] stringValue]];
}
}
}