【问题标题】:Converting XML to NSString将 XML 转换为 NSString
【发布时间】:2012-08-21 08:09:13
【问题描述】:

以前,我可以使用这种编码获取 URL 的内容:

<?xml version = "1.0" encoding = "UTF-8"?>

并将其解析为 NSString,代码如下:

NSMutableData *receivedData =  [[[NSMutableData alloc] initWithContentsOfURL:[NSURL URLWithString:authenticateURL]] autorelease];
    NSString *string = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];if (string) {   // if connection established, string will look for <error> in XML
        NSRange range = [string rangeOfString:@"<error>"];
        if (range.location == NSNotFound) {
            result = TRUE;
            NSLog(@"Authenticated!");  // if <error> not found, record is present
        }                           //return TRUE to load data
        else {
            result = FALSE;         // <error> found in XML, record is not found
            NSLog(@"Not Authenticated!");
        }
    }

但是,我现在需要获取的内容实际上是没有编码类型的,例如:

&lt;?xml version="1.0" ?&gt;&lt;authenticate&gt;&lt;auth&gt;Y&lt;/auth&gt;&lt;/authenticate&gt;

因此,当我 NSLog 字符串时,它是空的。已经尝试搜索其他方法,但我发现的所有示例,人们都可以使用 UTF8StringEncoding。很高兴有任何建议:)!谢谢!

【问题讨论】:

  • 你应该使用 NSXMLParser 类
  • @elppa 编辑了我的代码以显示我实际在做什么。嗯,我不想做所有的解析,我只想将 XML 转换为字符串,在那个字符串中我找到 ,这更容易。因此,如果在该字符串中未发现错误,则该人将通过身份验证。 :)
  • 谢谢大家,我猜只是编码问题阻止了我检索代码

标签: iphone ios xml encoding nsmutabledata


【解决方案1】:

您可以将开源库 TBXML 与https://gist.github.com/1922643 结合使用,将接收到的 XML 转换为 NSDictionary。它支持 NSData(使用 NSUTF8StringEncoding)和普通 NSStrings。

此 NSDictionary 包含 XML 中可用的所有信息,您可以使用 objectForKey: 函数读取它。

【讨论】:

    【解决方案2】:

    你应该使用 NSXMLParser 或者使用现成的解析器http://www.developers-life.com/simple-xml-parser-based-on-nsxmlparser-converter.html

    【讨论】:

      【解决方案3】:

      您可以使用NSXMLParser class

      这是一个很好的 Tutorial 向你展示如何使用这个类

      【讨论】:

      • 我想与我应该获取的 XML 有点不同。在本教程中,xml 使用 ,UTF-8 编码。对于 UTF-8 编码,我可以将其转换为 NSString 没问题。但是由于我现在需要处理的编码是 ,我迷路了。无论如何感谢您的建议:)
      【解决方案4】:

      对不起,实际上我无法从 URL 中检索 XML 的原因是因为一些 SSL 问题。我使用的解决方案可以在这里找到:How to use NSURLConnection to connect with SSL for an untrusted cert?

      也感谢大家的帮助^^

      【讨论】:

        猜你喜欢
        • 2015-10-30
        • 2017-03-08
        • 2016-01-17
        • 2012-02-29
        • 2011-02-04
        • 2011-04-24
        • 2013-10-19
        • 2017-04-23
        相关资源
        最近更新 更多