Objective-C报”NSXMLParserEntityRefMissingSemiError”异常的原因和解决办法

  • Post category:IOS

此异常是NSXMLParser类的一个错误,它指示XML解析器在处理实体引用时缺少了分号。一些XML文件中在实体引用后少了分号可能会导致出现此错误。解决这个错误的方法是确保所有实体引用之后都包含一个分号。

以下是两个示例说明:

示例1

NSString *xmlString = @"<?xml version='1.0' encoding='UTF-8'?><book><title>The Lion, the Witch and the Wardrobe</title><author>C. S. Lewis</author><published_year>1950<published_year><genre>fantasy<genre></book>";
NSData *xmlData = [xmlString dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:xmlData];
xmlParser.delegate = self;
[xmlParser parse];

如果在XML文档中缺少分号,会抛出”NSXMLParserEntityRefMissingSemiError”异常。例如以下XML字符串在published_year元素中缺少了分号。

NSString *xmlString = @"<?xml version='1.0' encoding='UTF-8'?><book><title>The Lion, the Witch and the Wardrobe</title><author>C. S. Lewis</author><published_year>1950</published_year><genre>fantasy</genre></book>";

应该这样更正:

NSString *xmlString = @"<?xml version='1.0' encoding='UTF-8'?><book><title>The Lion, the Witch and the Wardrobe</title><author>C. S. Lewis</author><published_year>1950</published_year><genre>fantasy</genre></book>";

示例2

在XML文档中,字符实体引用由”&”和实体名称或实体号码组成,实体号码则由’#’和十进制数字组成。实体引用必须以’;’结尾,否则会导致出现”NSXMLParserEntityRefMissingSemiError”异常。

例如,在以下XML字符串中,&lt字符实体引用没有以’;’结尾:

NSString *xmlString = @"<?xml version='1.0' encoding='UTF-8'?><book><title>The Lion, the Witch and the Wardrobe</title><author>C. S. Lewis</author><description>In <em>The Chronicles of Narnia</em> series, a group of children travels to a magical land through a wardrobe.</description></book>";

应该这样更正:

NSString *xmlString = @"<?xml version='1.0' encoding='UTF-8'?><book><title>The Lion, the Witch and the Wardrobe</title><author>C. S. Lewis</author><description>In <em>The Chronicles of Narnia</em> series, a group of children travels to a magical land through a wardrobe.</description></book>";