iPhone xml 反序列化器

发布于 2024-12-10 12:51:38 字数 573 浏览 0 评论 0原文

我是编程新手,这是我的第一个项目,所以我对 xml 解析等不太了解。 我需要解析一个 xml 文档,就像......

<TLMS><TLMSResponse status="SUCCESS">
 <books>
  <book>
   <name>abc</name>
   <author>DEF</author>
   <publisher>HIJ</publisher>
  </book>

  <book>
   <name>xyz</name>
   <author>rus</author>
   <publisher>tuv</publisher>
  </book>
 </books>
</TLMSResponse></TLMS>

我已经尝试了很多,但还没有找到任何好的反序列化器可以解析这个 xml 并创建“Book”类的对象。 非常感谢任何帮助...

谢谢大家

I am new to programming and this is my first project so I don't have much idea about xml parsing etc.
I need to parse an xml document like...

<TLMS><TLMSResponse status="SUCCESS">
 <books>
  <book>
   <name>abc</name>
   <author>DEF</author>
   <publisher>HIJ</publisher>
  </book>

  <book>
   <name>xyz</name>
   <author>rus</author>
   <publisher>tuv</publisher>
  </book>
 </books>
</TLMSResponse></TLMS>

I have tried a lot but haven't found any good de-serializer that can parse this xml and make objects of "Book" class.
Any help is greatly appreciated...

Thank You all

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

a√萤火虫的光℡ 2024-12-17 12:51:38

这是一个实现 NSXMLParserDelegate 的示例类 协议。

它将将此 xml: 解析

<TLMS><TLMSResponse status="SUCCESS">
<books>
<book>
<name>abc</name>
<author>DEF</author>
<publisher>HIJ</publisher>
</book>

<book>
<name>xyz</name>
<author>rus</author>
<publisher>tuv</publisher>
</book>
</books>
</TLMSResponse></TLMS>

为字典数组,每个字典都是 xml 中的一本“书”,其中包含每个标签的键以及该标签之间的文本作为键的值。因此,[_delegate receiveParsedData:[returnData autorelease] withIdent:ident]; 中的 returnData 看起来像这样:

array = 
(
    {
        name:"abc",
        author:"DEF",
        publisher:"HIJ",
    },
    {
        name:"xyz",
        author:"rus",
        publisher:"tuv",
    },
)

JHXMLParser.h

@protocol JHXMLParserDelegate;

@interface JHXMLParser : NSObject <NSXMLParserDelegate> {
    NSString *ident;

    @private
    id _delegate;
    NSMutableArray *_parsedData;
    NSString *_key;
    NSXMLParser *_dataParser;
    NSString *_previousTag;
    NSString *_currentTag;
    NSMutableString *_elementText;
}

@property (nonatomic, retain) NSString *ident;

- (id)initWithKey:(NSString *)Key andData:(NSData *)data;
// delegate management. The delegate is not retained.
- (id <JHXMLParserDelegate>)delegate;
- (void)setDelegate:(id <JHXMLParserDelegate>)delegate;
- (BOOL)start;

@end

@protocol JHXMLParserDelegate <NSObject>

@optional
- (void)acceptParsedData:(NSMutableArray *)parsedData withIdent:(NSString *)ident;

@end

JHXMLParser.m

#import "JHXMLParser.h"

@implementation JHXMLParser

@synthesize ident;

- (id)init {
    if ((self = [super init])) {
        ident = [[NSString alloc] init];
    }
    return self;
}

- (id)initWithKey:(NSString *)key andData:(NSData *)data {
    if ((self = [self init])) {
        _key = key;
        _elementText = [[NSMutableString alloc] initWithString:@""];
        _dataParser = [[NSXMLParser alloc] initWithData:data];
        _dataParser.delegate = self;
    }
    return self;
}

- (id <JHXMLParserDelegate>)delegate {
    id <JHXMLParserDelegate> d = nil;
    if (_delegate) {
        d = _delegate;
    }
    return d;
}
- (void)setDelegate:(id <JHXMLParserDelegate>)delegate {
    _delegate = delegate;
}

- (BOOL)start {
    return [_dataParser parse];
}

- (void)dealloc {
    [ident release];
    [_dataParser release];
    [_parsedData release];
    [_elementText release];
    [_previousTag release];
    [_currentTag release];
    [super dealloc];
}

#pragma mark - NSXMLParser Delegate

- (void)parserDidStartDocument:(NSXMLParser *)parser {
    _parsedData = [[NSMutableArray alloc] init];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    if (_currentTag) {
        [_currentTag release], _currentTag = nil;
    }
    _currentTag = [[NSString alloc] initWithString:elementName];
    if ([elementName isEqualToString:_key]) {
        NSMutableDictionary *tmpDict = [[NSMutableDictionary alloc] init];
        [_parsedData addObject:tmpDict];
        [tmpDict release];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    if ([_previousTag isEqualToString:_currentTag]) {
        [_elementText appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
    } else {
        if (_elementText) {
            [_elementText release], _elementText = nil;
        }
        _elementText = [[NSMutableString alloc] initWithString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
    }
    if (![_previousTag isEqualToString:_currentTag]) {
        if (_previousTag) {
            [_previousTag release], _previousTag = nil;
        }
        _previousTag = [[NSString alloc] initWithString:_currentTag];
    }
    [pool drain];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    if ([_previousTag isEqualToString:elementName]) {
        [[_parsedData lastObject] setObject:_elementText forKey:elementName];
    } else {
        if (_previousTag) {
            [_previousTag release], _previousTag = nil;
        }
        _previousTag = [[NSString alloc] initWithFormat:@""];
    }
    [pool drain];
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
    NSMutableArray *returnData = [[NSMutableArray alloc] initWithArray:_parsedData];
    if ([_delegate respondsToSelector:@selector(acceptParsedData:withIdent:)]) {
        [_delegate acceptParsedData:[returnData autorelease] withIdent:ident];
    } else {
        [returnData release], returnData = nil;
    }
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSLog(@"********** ERROR Parsing (%@) XML Data! - %@ - %@ **********", ident, [parseError localizedDescription], [parseError localizedFailureReason]);
    if ([_delegate respondsToSelector:@selector(acceptParsedData:withIdent:)]) {
        [_delegate acceptParsedData:_parsedData withIdent:ident];
    }
}

@end

Here's an example class implementing the NSXMLParserDelegate protocol.

It would parse this xml:

<TLMS><TLMSResponse status="SUCCESS">
<books>
<book>
<name>abc</name>
<author>DEF</author>
<publisher>HIJ</publisher>
</book>

<book>
<name>xyz</name>
<author>rus</author>
<publisher>tuv</publisher>
</book>
</books>
</TLMSResponse></TLMS>

into an array of dictionaries, each dictionary is a "book" from the xml with keys for each tag and the text between that tag as the value for the key. So this is how the returnData in [_delegate acceptParsedData:[returnData autorelease] withIdent:ident]; would look like:

array = 
(
    {
        name:"abc",
        author:"DEF",
        publisher:"HIJ",
    },
    {
        name:"xyz",
        author:"rus",
        publisher:"tuv",
    },
)

JHXMLParser.h

@protocol JHXMLParserDelegate;

@interface JHXMLParser : NSObject <NSXMLParserDelegate> {
    NSString *ident;

    @private
    id _delegate;
    NSMutableArray *_parsedData;
    NSString *_key;
    NSXMLParser *_dataParser;
    NSString *_previousTag;
    NSString *_currentTag;
    NSMutableString *_elementText;
}

@property (nonatomic, retain) NSString *ident;

- (id)initWithKey:(NSString *)Key andData:(NSData *)data;
// delegate management. The delegate is not retained.
- (id <JHXMLParserDelegate>)delegate;
- (void)setDelegate:(id <JHXMLParserDelegate>)delegate;
- (BOOL)start;

@end

@protocol JHXMLParserDelegate <NSObject>

@optional
- (void)acceptParsedData:(NSMutableArray *)parsedData withIdent:(NSString *)ident;

@end

JHXMLParser.m

#import "JHXMLParser.h"

@implementation JHXMLParser

@synthesize ident;

- (id)init {
    if ((self = [super init])) {
        ident = [[NSString alloc] init];
    }
    return self;
}

- (id)initWithKey:(NSString *)key andData:(NSData *)data {
    if ((self = [self init])) {
        _key = key;
        _elementText = [[NSMutableString alloc] initWithString:@""];
        _dataParser = [[NSXMLParser alloc] initWithData:data];
        _dataParser.delegate = self;
    }
    return self;
}

- (id <JHXMLParserDelegate>)delegate {
    id <JHXMLParserDelegate> d = nil;
    if (_delegate) {
        d = _delegate;
    }
    return d;
}
- (void)setDelegate:(id <JHXMLParserDelegate>)delegate {
    _delegate = delegate;
}

- (BOOL)start {
    return [_dataParser parse];
}

- (void)dealloc {
    [ident release];
    [_dataParser release];
    [_parsedData release];
    [_elementText release];
    [_previousTag release];
    [_currentTag release];
    [super dealloc];
}

#pragma mark - NSXMLParser Delegate

- (void)parserDidStartDocument:(NSXMLParser *)parser {
    _parsedData = [[NSMutableArray alloc] init];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    if (_currentTag) {
        [_currentTag release], _currentTag = nil;
    }
    _currentTag = [[NSString alloc] initWithString:elementName];
    if ([elementName isEqualToString:_key]) {
        NSMutableDictionary *tmpDict = [[NSMutableDictionary alloc] init];
        [_parsedData addObject:tmpDict];
        [tmpDict release];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    if ([_previousTag isEqualToString:_currentTag]) {
        [_elementText appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
    } else {
        if (_elementText) {
            [_elementText release], _elementText = nil;
        }
        _elementText = [[NSMutableString alloc] initWithString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
    }
    if (![_previousTag isEqualToString:_currentTag]) {
        if (_previousTag) {
            [_previousTag release], _previousTag = nil;
        }
        _previousTag = [[NSString alloc] initWithString:_currentTag];
    }
    [pool drain];
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    if ([_previousTag isEqualToString:elementName]) {
        [[_parsedData lastObject] setObject:_elementText forKey:elementName];
    } else {
        if (_previousTag) {
            [_previousTag release], _previousTag = nil;
        }
        _previousTag = [[NSString alloc] initWithFormat:@""];
    }
    [pool drain];
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
    NSMutableArray *returnData = [[NSMutableArray alloc] initWithArray:_parsedData];
    if ([_delegate respondsToSelector:@selector(acceptParsedData:withIdent:)]) {
        [_delegate acceptParsedData:[returnData autorelease] withIdent:ident];
    } else {
        [returnData release], returnData = nil;
    }
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSLog(@"********** ERROR Parsing (%@) XML Data! - %@ - %@ **********", ident, [parseError localizedDescription], [parseError localizedFailureReason]);
    if ([_delegate respondsToSelector:@selector(acceptParsedData:withIdent:)]) {
        [_delegate acceptParsedData:_parsedData withIdent:ident];
    }
}

@end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文