<?xml version="1.0" encoding="utf-8" ?> 表示XML文件版本, 內部文本使用的編碼
<root> 表示根節點
<CityName>北京</CityName> 北京 一個結點, CityName是結點名, 北京結點值
<Item key="1" value="A"></Item> key="1"是結點屬性, key屬性名, "1"屬性值
注意: XML結構理解為層層嵌套的樹形結構
<?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>
//(1)添加頭文件搜索路徑 // Header Search Paths-> /usr/include/libxml2 //(2)添加二進制庫 // Link library -> lixml2.dylib //(3)源文件添加編譯選項 // -fno-objc-arc //(4)添加頭文件 // #import "GDataXMLNode.h"
//1.加載和解析XML文件 NSString *path = [[NSBundle mainBundle] pathForResource:@"xml.txt" ofType:nil]; NSData *data = [[NSData alloc] initWithContentsOfFile:path]; //GDataXMLDocument 表示XML文檔對象 //initWithData 使用NSData初始化,就是解析 GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:data options:0 error:nil]; //2.獲取指令語法 XPath //CityName路徑: /root/systemConfig/CityName NSArray *array = [doc nodesForXPath:@"/root/systemConfig/CityName" error:nil]; GDataXMLElement *element = [array firstObject]; NSLog(@"name = %@ value = %@",element.name,element.stringValue); //獲取指定節點的屬性 NSArray *items = [doc nodesForXPath:@"/root/systemConfig/ComeChannel/Item" error:nil]; GDataXMLElement *item = [items firstObject]; //取屬性,屬性使用GDataXMLElement表示 for(GDataXMLElement *attr in item.attributes) { NSLog(@"name = %@ value = %@",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.childrenCount //獲取指定名字的子節點 //root elementsForName
鏈接網址:http://www.companysz.com.cn/xpath/xpath_syntax.asp
新聞熱點
疑難解答