【问题标题】:how to parse xml response in objective c如何在目标c中解析xml响应
【发布时间】:2017-10-10 08:34:47
【问题描述】:

我正在从服务器获取 xml 类型的响应,但我无法通过解析 do no 获取我缺少的东西的值

这是来自服务器的示例响应:

<admin>
<logindetails 
status="cdcdvfbgfhgfgfbff" 
timestamp="1494499694240" isdaylighton="true" 
isupdateavailable="false" updateurl="" user="1" 
userParentID="0">Success</logindetails><admin>

我的解析方法:

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSLog(@"Element Name :%@",elementName);

recordResults =NO;

if ([elementName isEqualToString:@"logindetails"]) {

    data = [soapResultsString dataUsingEncoding:NSUTF8StringEncoding];
    json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSLog(@"json===>%@",array);
  }
}

 -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
 {

if( recordResults )
{
    [childElement appendString: string];
    NSLog(@"inside%@",string);

}

}

 -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
  attributes: (NSDictionary *)attributeDict
{

xmlparserString=elementName;
NSLog(@"xmlparserString start -->%@",xmlparserString);

if( [xmlparserString isEqualToString:@"logindetails"])
{

    recordResults =YES;
    soapResultsString = [[NSMutableString alloc] init];

}

}

我正在获取所有标签名称,但我无法从 Xml 响应中获取值,请检查代码并回答

【问题讨论】:

  • 如果它以字符串形式出现,您可以进行字符串操作,否则您可以将它们转换为字典。在 git xml 到字典中,有一个框架工作。在您的应用程序中导入该框架并将 xml 转换为字典,然后您可以根据需要使用它。
  • 元素是标签,数据是标签中包含的内容......除非你有一些疯狂的自定义奇怪的 XML,否则这不是应该的。无论如何,您都希望将标签遍历到关联模型中。 XML JSON/Hashable Dictionary 是不可能的,因为 XML 可以表示 JSON 不能表示的结构。

标签: ios objective-c nsxmlparser


【解决方案1】:

您要查找的数据是XML 属性,并在didStartElementattributes 字典中返回。

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *) elementName 
                                       namespaceURI:(NSString *) namespaceURI 
                                      qualifiedName:(NSString *) qName
                                         attributes:(NSDictionary *) attributeDict
{

    xmlparserString = elementName;
    NSLog(@"xmlparserString start -->%@",xmlparserString);

    if ([xmlparserString isEqualToString:@"logindetails"]) {

        // soapResultsString = [[NSMutableString alloc] init];
        NSLog(@"logindetails attributes --> %@", attributeDict);

}

didEndElement 中的 JSON 反序列化错误,无法正常工作。 XML 属性不是 JSON。删除整个if 表达式

【讨论】:

  • 我得到了这个 { isdaylighton = true; isupdateavailable = 假;状态=“dsfdvvfbfdg”;时间戳 = 1494504256966;更新网址 = "";用户父 ID = 0;用户特权 = 1; } 从这里如何获取单个值
  • 这是一个标准字典(键/值对)。例如你得到1attributeDict[@"userPrivilege"]
猜你喜欢
  • 1970-01-01
  • 2011-09-19
  • 2011-10-22
  • 2021-06-07
  • 1970-01-01
  • 2011-05-13
  • 2019-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多