iPhone TBXML循环和解析数据

时间:2011-03-23 14:03:42

标签: iphone objective-c cocoa-touch ios ios4

基本上我有一个返回的XML响应和一个字符串,我需要遍历xml并将所有信息存储在一个数组中。这是xml

<?xml version="1.0" encoding="UTF-8"?>
<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://schema.2sms.com/2.0/schema/0310_ResponseReportStandard.xsd" Version="1.0">
    <Error>
        <ErrorCode>00</ErrorCode>
        <ErrorReason>OK</ErrorReason>
    </Error>
    <ResponseData>
        <Identification>
            <UserID>jonathan.pink@2sms.com</UserID>
        </Identification>
        <Result>2 records were returned</Result>
        <Detail>
            <ReportTitle>Message Summary: Today</ReportTitle>
            <Record>
                <Destination>447790686158</Destination>
                <Status>WithNetwork</Status>
                <GUID><![CDATA[2011-03-22T10:54:22.097Z]]></GUID>
                <DateSubmitted>2011-03-22T10:54:22.097</DateSubmitted>
                <DateToSend></DateToSend>
                <DateSent>2011-03-22T10:54:22.533</DateSent>
                <DateReceived></DateReceived>
                <Message><![CDATA[Yet again another test]]></Message>
                <ID>2011-03-22 10:54:22.250HIHIIOJTFVETW85TS</ID>
            </Record>
            <Record>
                <Destination>447790686158</Destination>
                <Status>SUCCESS</Status>
                <GUID><![CDATA[2011-03-22T10:50:40.064Z]]></GUID>
                <DateSubmitted>2011-03-22T10:50:40.063</DateSubmitted>
                <DateToSend></DateToSend>
                <DateSent>2011-03-22T10:50:42.473</DateSent>
                <DateReceived>2011-03-22T10:50:54.570</DateReceived>
                <Message><![CDATA[This is a test]]></Message>
                <ID>2011-03-22 10:50:40.210DRUDVMCEZGETW85TS</ID>
            </Record>
            <ReportPage ReportID="775797" ItemsPerPage="25" Page="1" TotalItems="2" />
        </Detail>
    </ResponseData>
</Response>

我需要将那些2 <records>和所有数据存储在一个数组中。所以....

记录数组 - &gt;记录数组 - &gt;每个记录的数组,数据......

我一直坐在这里试图使用TBXML来解决这个问题,这很容易抓住一个节点....但我不能这样做:(

4 个答案:

答案 0 :(得分:14)

好的,你的第一步是创建一个解析数据的类。例如,将其称为RecordParser。我们现在需要在标题中添加几个方法,以及NSMutableArray

@interface RecordParser : NSObject {
    NSMutableArray *records;    
}
@property(nonatomic,retain)NSMutableArray *records;

-(void)loadRecords:(NSString *)records;
-(void)traverseElement:(TBXMLElement *)element;

@end

现在,请继续并充实您的实施。我们现在需要实现这两种方法来完成我们希望他们做的事情。

- (void)loadRecords:(NSString *)records {
    NSString *someXML = @"http://www.something.com/somexml.xml";
    TBXML *tbxml = [[TBXML tbxmlWithURL:[NSURL URLWithString:someXML]] retain];

    records = [NSMutableArray array];
    [records retain];

    if (tbxml.rootXMLElement)
        [self traverseElement:tbxml.rootXMLElement];
    [tbxml release];
}

基本上该方法将获取有问题的XML文件并开始解析过程。此外,您正在初始化阵列并保留它。现在我们来到奶酪。

- (void) traverseElement:(TBXMLElement *)element {
    do {
        if (element->firstChild) 
            [self traverseElement:element->firstChild];

        if ([[TBXML elementName:element] isEqualToString:@"Record"]) {
            TBXMLElement *destination = [TBXML childElementNamed:@"Destination" parentElement:element];
            TBXMLElement *status = [TBXML childElementNamed:@"Status" parentElement:element];
            TBXMLElement *guid = [TBXML childElementNamed:@"GUID" parentElement:element];
            TBXMLElement *dateSub = [TBXML childElementNamed:@"DateSubmitted" parentElement:element];
            TBXMLElement *dateToSend = [TBXML childElementNamed:@"DateToSend" parentElement:element];
            TBXMLElement *dateSent = [TBXML childElementNamed:@"DateSent" parentElement:element];
            TBXMLElement *dateReceived = [TBXML childElementNamed:@"DateReceived" parentElement:element];
            TBXMLElement *message = [TBXML childElementNamed:@"Message" parentElement:element];
            TBXMLElement *id = [TBXML childElementNamed:@"ID" parentElement:element];

            [records addObject:[NSArray arrayWithObjects:
                                  [TBXML textForElement:destination],
                                  [TBXML textForElement:status],
                                  [TBXML textForElement:guid],
                                  [TBXML textForElement:dateSub],
                                  [TBXML textForElement:dateToSend],
                                  [TBXML textForElement:dateSent],
                                  [TBXML textForElement:dateReceived],
                                  [TBXML textForElement:message],
                                  [TBXML textForElement:id],nil]];  
        }
    } while ((element = element->nextSibling));  
}

基本上,该方法的作用是横向查找具有您正在寻找的名称的元素的XML文件,然后它从子节点获取数据。此外,数据将添加到records数组中。所以基本上,当它完成时,它应该在你的records数组中拥有你想要的数据,你可以操作你想要的所有数据。

这是完全未经测试的。如果它炸毁你的电脑并杀死你的猫,不要怪我。我通常不会把所有的工作都写成这样的完整方法,但我碰巧喜欢TBXML。如果有效,请告诉我。我非常会很高兴知道。

答案 1 :(得分:1)

我编写了递归函数来解析任何使用TBXML库正确创建的xml。

在我的项目中,我有一个解析XML的类。它有一个名为的类方法:+(id)infoOfElement:(TBXMLElement *)element

使用方法:

TBXML *tbxml = [TBXML tbxmlWithXMLData:yourData];
TBXMLElement *rootXMLElement = tbxml.rootXMLElement;

id parsedData = [self infoOfElement: rootXMLElement];

    //return NSString or NSDictionary ot NSArray of parsed data
    + (id) infoOfElement: (TBXMLElement*) element
    {
        if (element->text)
            return [TBXML textForElement:element];
        NSMutableDictionary *info = [NSMutableDictionary new];
        TBXMLAttribute *attribute = element->firstAttribute;
        if (attribute) {
            do {
                [info setValue:[TBXML attributeValue:attribute] forKey:[TBXML attributeName:attribute]];
                attribute = attribute -> next;
            } while (attribute);
        }
        TBXMLElement *child = element->firstChild;
        if (child){
            TBXMLElement *siblingOfChild = child->nextSibling;
            //If we have array of children with equal name -> create array of this elements
            if ([[TBXML elementName:siblingOfChild] isEqualToString:[TBXML elementName:child]]){
                NSMutableArray *children = [NSMutableArray new];
                do {
                    [children addObject:[self infoOfElement:child]];
                    child = child -> nextSibling;
                } while (child);
                return [NSDictionary dictionaryWithObject:children forKey:[TBXML elementName:element]];
            }
            else{
                do {
                    [info setValue:[self infoOfElement:child] forKey:[TBXML elementName:child]];
                    child = child -> nextSibling;
                } while (child);
            }
        }            
        return info;
    }

答案 2 :(得分:0)

使用Apple的NSXMLParser;它是老式的,除了它真的很有效。

相应地设置XMLParser(使用NSXMLParserDelegate协议)。

解析器点击后,调用parser:didStartElement:namespaceURI:qualifiedName:attributes:代理人回拨,elementName等于Record(根据您的需要)。

Alloc'init'一个NSMutableDictionary。如上所述,如果elementName等于Destination,那么[myDictionary setObject: elementName forKey: @"Destination"]和等等。

希望有所帮助:)。

小方注意:更喜欢使用Apple's“技术”代替第三方:它更有效,可能性 无穷无尽

答案 3 :(得分:-2)

最好使用NSXMLParser,因为它是Apple的正式版本。

NSXMLParser的所有文档都是here

此外,这是一个NSXMLParser Tutorial