以指定格式 iOS 解析 XML 文件

Parse a XML file in a specified format iOS

我是否可以通过它来解析以下格式的 XML 文件:-

<?xml version="1.0" encoding="utf-8"?>
<CountryList>
  <Country CountryId="AF">Afghanistan</Country>
  <Country CountryId="AX">Akrotiri</Country>
  <Country CountryId="AL">Albania</Country>
...........................................
...........................................

我需要国家 ID 和名称:- 即 "AL" 和 "Albania"所以,是否可以解析指定 XML,并将 Country Id 和国家名称存储在一个数组中。 任何建议都会有所帮助。

使用 NSDictionary(value for key) 保存值。您可以使用此库获取和保存值:

Parse XML 您可以在上述页面上找到提取所需数据的所有说明。

在 Omer Waqas Khan link 的帮助下,只需发布​​代码,您显然可以从以下 link [=14] 中找到 XMLDictionary class =]nicklockwood/XMLDictionary


#import "XMLDictionary.h"

 NSString *filePath = [[NSBundle mainBundle] pathForResource:@"EDUCountry" ofType:@"xml"];
 NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLFile:filePath];
 NSLog(@"xmlDOC=%@",xmlDoc);
 NSArray *arr=[xmlDoc valueForKey:@"Country"];
 NSLog(@"Country Name and code=%@",[arr objectAtIndex:4]); 

您可以使用 NSXmlParser

解析此 xml

使用以下方法:

  1. didStartElement

  2. foundCharacters

您可以在 attributeDict

中获得 CountryId
Swift code:

didStartElement方法中:

currentElement = elementName // currentElement is global variable which store the current element name 
if elementName == "Country"
{
let id = attributeDict["CountryId"] as? NSString // attributeDict is parameter variable in didStartElement method
// here you can store id in array
}

If any tag containt value then it will call foundCharacters method

在 foundCharacters 方法中编写如下代码:

if currentElement == "Country"
{
// store country name from here to array there is paramenter name `string` in `foundCharacters` method
}