无法解析以下XML?

时间:2012-06-11 04:22:07

标签: iphone objective-c ios xml-parsing nsxmlparser

我有img id="#"的连续标记,其中#从1到9不等。

标签的描述由浮动值组成。

当我使用标准的NSXML Parser时,我没有得到所有的值。

我的XML供参考:

<img id="1">-0.0111328,-0.0635608,0.152549,0.11211,-0.0250431,

            -0.0370875,0.0862391,0.0970791,-0.0195908,

            -0.00892297,0.0791795,0.0554013,0.00362028,0.0138572,0.0432729,

             0.0253036,-0.0770325,0.14065,0.118424,0.1787,

             0.0734354,0.160883,0.101831,0.237038,0.0681151,0.178331,

             0.106532,0.224731,0.133766,0.222096,0.165214,0.240752,

             -0.0280366,0.106239,0.052094,0.110642,   

</img>

我如何解析上面的XML?

请帮助我。

感谢名单

2 个答案:

答案 0 :(得分:2)

这是因为parser:foundCharacters:不会一次传递所有字符。您需要连接在parser:didStartElement:namespaceURI:qualifiedName:attributes:标记的parser:didEndElement:namespaceURI:qualifiedName:<img>的回调之间获得的所有字符串。

在下面的代码中,buf是解析器代理的NSMutableString ivar。

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    if ([qualifiedName isEqualToString:@"img"]) {
        buf = [NSMutableString string];
    }
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if ([qualifiedName isEqualToString:@"img"]) {
        buf = [buf stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSLog(@"Got %@", buf);
    }
}

- (void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    [buf appendString:string];
}

答案 1 :(得分:0)

终于搞定了......我为img id ='#'放置了开始和结束标签。我的结构现在看起来像这样:

<images>

    <img id = '1'> -0.0111328,-0.0635608,0.152549,0.11211,-0.0250431,

        -0.0370875,0.0862391,0.0970791,-0.0195908,

        -0.00892297,0.0791795,0.0554013,0.00362028,0.0138572,0.0432729,

         0.0253036,-0.0770325,0.14065,0.118424,0.1787,

         0.0734354,0.160883,0.101831,0.237038,0.0681151,0.178331,

         0.106532,0.224731,0.133766,0.222096,0.165214,0.240752,

         -0.0280366,0.106239,0.052094,0.110642, ....  

     </img>

     <img id = '2'> ... 

     </img>

   ....

   ....

</images>

<mapping>

  <map>
    <imgid> 1 </imgid>
    <keyword> heavy </keyword>

  </map>

  <map>
    <imgid> 2 </imgid>
    <keyword> metal </keyword>

  </map>

  ...

  ...

</mapping>

放置开始和结束标记允许我解析整个xml。

早些时候,开始和结束标记是针对单个图像的,只会导致解析一个img。

这使我在解析XML时添加了另一个关键点。

希望这也有助于其他人。