标签:
<?xml version="1.0" encoding="utf-8" ?> version表示版本,encoding="utf-8"表示内部文本使用的编码
<root> 表示根结点
<CityName>北京</CityName> <CityName>北京 --- <CityName> :节点名 , 北京 :结点值
<Item key="1" value="A"></Item> key="1"是结点属性, key属性名, "1"属性值
<?xml version="1.0" encoding="utf-8" ?> <root> <systemConfig> <CityName>北京</CityName> <CityCode>201</CityCode> <ParentCityCode> 0</ParentCityCode> <areaCode>010</areaCode> <AgreementUrl></AgreementUrl> <IntentionLevel> <Item key="1" value="A"></Item> <Item key="2" value="B"></Item> <Item key="3" value="C"></Item> </IntentionLevel> <ComeChannel> <Item key="1" value="报纸"></Item> <Item key="2" value="杂志"></Item> </ComeChannel> <BuyCarBudget> <Item key="1" value="40-50万"></Item> <Item key="2" value="50-60万"></Item> </BuyCarBudget> <IntentionColor> <Item key="1" value="红"></Item> <Item key="2" value="黄"></Item> </IntentionColor> </systemConfig> </root>
常用的XML解析方式
(1)unix - libxml2 C接口
(2)NSXMLParser UI提供的XML解析库, 使用比较麻烦
(3)google开发GData
NSString *path = [[NSBundle mainBundle] pathForResource:@"xml.txt" ofType:nil]; NSData *data = [[NSData alloc] initWithContentsOfFile:path]; GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil]; //2.获取指定结点 //CityName路径:/root/systemConfig/CityName NSArray *array = [doc nodesForXPath:@"/root/systemConfig/CityName" error:nil]; GDataXMLElement *element = [array firstObject]; NSLog(@"name = %@,value = %@",element.name,element.stringValue); //3.获取指定结点的属性 NSArray *items = [doc nodesForXPath:@"/root/systemConfig/ComeChannel/Item" error:nil]; GDataXMLElement *item = [items firstObject]; //获取属性,属性使用GDataXMLElement for(GDataXMLElement *attr in item.attributes) { NSLog(@"a-name =%@ avalue = %@",attr.name,attr.stringValue); } //4.获取所有指定名字的结点,而不管位置 //XPath语法://Item NSArray *allItem = [doc nodesForXPath:@"//Item" error:nil]; for(GDataXMLElement *e in allItem) { NSLog(@"name =%@",e.name); } //5.获取所有指定名字的属性(不管哪个结点) ////XPath语法://@value NSArray *allvalue = [doc nodesForXPath:@"//@value" error:nil]; for(GDataXMLElement *e in allvalue) { NSLog(@"value = %@",e.stringValue); } //6.逐层遍历XML文件 //获取根结点 GDataXMLElement *root = doc.rootElement; //获取子节点 //root.children //获取子节点个数 //root.childCount //获取指定名字的子节点 //root elementsForName:(NSString *)
标签:
原文地址:http://www.cnblogs.com/SuperHanks/p/4390383.html