XML屬性元素值解析我的XML結構如下:如何設置鍵值對中的NSMutableDictionary因爲我使用<strong>的NSXMLParser</strong>使用的NSXMLParser
<characters>
<character>
<literal>本</literal>
<codepoint>
<cp_value cp_type="ucs">672c</cp_value>
<cp_value cp_type="jis208">43-60</cp_value>
</codepoint>
</character>
</characters>
我想用cp_value
元素的attribute_value作爲鍵和元素值(例如672c)作爲值並將此鍵值對放置在我的NSMutableDictionary
*_codepoint
中。解析後,我想要的結果(在控制檯)看起來像這樣:
_codepoint: {
"ucs"=672c;
"jis208"=43-60;
}
正如我已經實現瞭解析器(代碼如下),我得到這個早在控制檯:
2013-01-22 22:12:46.199 MyApp[13391:c07] _codepoint: {
ucs = "\n \n ";
}
2013-01-22 22:12:46.201 MyApp[13391:c07] _codepoint: {
jis208 = "\n \n 672c\n ";
}
首先 - 值和鍵不同步,其次,jis208元素的值未被讀入。其次,我不確定這些\ n和空格是什麼。任何人都可以提出一些建議嗎?
我寫的代碼是:
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
if([elementName isEqualToString:@"characters"]) {
appDelegate.characters = [[NSMutableArray alloc] init];
} else if ([elementName isEqualToString:@"character"]) {
aCharacter = [[Character alloc] init];
} else if ([elementName isEqualToString:@"cp_value"]) {
if (!_codepoint) _codepoint = [[NSMutableDictionary alloc] init];
[_codepoint setValue:currentElementValue forKey:[attributeDict valueForKey:[[attributeDict allKeys] lastObject]]];
NSLog(@"_codepoint: %@", _codepoint);
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if (!currentElementValue) {
currentElementValue = [[NSMutableString alloc] initWithString:string];
} else {
[currentElementValue appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"characters"]
// cp_values will be copied from a local NSMutableDictionary *_codepoint
|| [elementName isEqualToString:@"codepoint"]
) return;
if ([elementName isEqualToString:@"character"]) {
[appDelegate.characters addObject:aCharacter];
[aCharacter release];
} else if ([elementName isEqualToString:@"cp_value"]){
[aCharacter.codepoint addObject:_codepoint];
}
}
非常感謝您的期待。
試試我的答案.. –
我做到了。成功了!非常感謝你。 –