IPhone開發中,用libxml2解析xml字串

來源:互聯網
上載者:User

首先添加libxml2.dylib到工程中,再匯入標頭檔,#include <libxml/xmlreader.h>

再加入如下代碼:

-(NSMutableArray*)parser:(NSString*)xmlStr{
    //解析xml
    NSData *xmlData = [xmlStr dataUsingEncoding:NSUTF8StringEncoding];
xmlTextReaderPtr reader = xmlReaderForMemory([xmlData bytes], 
                                                 [xmlData length], 
                                                 NULL, nil, 
                                                 (XML_PARSE_NOBLANKS | XML_PARSE_NOCDATA | XML_PARSE_NOERROR | XML_PARSE_NOWARNING));
if (!reader) {
NSLog(@"Failed to load xmlreader");
return;
}
NSString *currentTagName = nil;
NSDictionary *currentPerson = nil;
NSString *currentTagValue = nil;
NSMutableArray *advertiseMArray = [NSMutableArray array];
char* temp;
while (true) {
if (!xmlTextReaderRead(reader)) break;
switch (xmlTextReaderNodeType(reader)) {
case XML_READER_TYPE_ELEMENT:
// starting an element
temp =  (char*)xmlTextReaderConstName(reader);
currentTagName = [NSString stringWithCString:temp 
                                                    encoding:NSUTF8StringEncoding];
if ([currentTagName isEqualToString:@"元素資訊"]) {
currentPerson = [NSMutableDictionary dictionary];
[advertiseMArray addObject:currentPerson];
                }
                
continue;
case XML_READER_TYPE_TEXT:
//The current tag has a text value, stick it into the current 
temp = (char*)xmlTextReaderConstValue(reader);
currentTagValue = [NSString stringWithCString:temp 
                                                     encoding:NSUTF8StringEncoding];
                
                if (!currentPerson) return;
                
                [currentPerson setValue:currentTagValue forKey:currentTagName];
                currentTagValue = nil;
currentTagName = nil;                              
                
            default: continue;
}
}
    

    // NSLog(@"%@:%s Final data: %@", [self class], _cmd, advertiseMArray );
    
    return advertiseMArray;
}

這裡返回的是一個mutableArray類型的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.