关于kissxml的简单使用

好久没有用过XML了,最近有项目需要用到XML,我就用了kissxml这个三方库,感觉还不错,比较简单,记录一下使用的方法免得忘了吧
下面是我随便截取的一段XML

<Config>
    <Cars name="中国车组" id="2" type="cargroup" bmp0="s2_1.png" bmp1="s2_2.png">
        <Car id="930">
            <icon>cnicon.png</icon>
            <log>cnlog.txt</log>
            <txt>安全气囊</txt>
            <ecu path="china/srsecu" name="930"/>
        </Car>
        <Car id="941">
            <icon>cnicon.png</icon>
            <log>cnlog.txt</log>
            <txt>水冷系统</txt>
            <ecu path="china/zhidou" name="941"/>
        </Car>
        <Car id="30">
            <icon>cnicon.png</icon>
            <log>cnlog.txt</log>
            <txt>发动机系统</txt>
            <ecu path="china/engsys" name="30"/>
        </Car>
        <Car id="917">
            <icon>cnicon.png</icon>0
            <log>cnlog.txt</log>
            <txt>防抱死刹车系统</txt>
            <ecu path="china/absecu" name="917"/>
        </Car>
    </Cars>
</Config>

怎样导入kissxml库之类的废话就不写了

//获取xml路径
 Nsstring *path = [[NSBundle mainBundle] pathForResource:XX.xml ofType:nil];
 //从xml读取数据
 NSData *data = [NSData dataWithContentsOfFile:path];
 //获取目录
 DDXMLDocument *xmlDoc = [[DDXMLDocument alloc] initWithData:data options:0 error:nil];
 //解析 这句话的意思是读取Config里面的Cars
  NSArray *cars = [xmlDoc nodesForXPath:@"//Config/Cars" error:nil];
  //遍历获取cars里面的成员
   for (DDXMLElement *element in cars) {
   //比如要获得cars里面的name,就这么写
   Nsstring *name = [[element attributeForName:@"name"] stringValue];//name=@"中国车组"
   //获得cars里面的每一个car
   NSArray *car = [element elementsForName:@"Car"];
   for (DDXMLElement *subElements in car) {
   //获取car的id
   Nsstring *carID = [[subElements attributeForName:@"id"] stringValue];
   //获取car里面的icon childAtIndex这个方法你可以理解成他是把car里面的成员都放进一个集合里,然后我们就通过下标获取对应的值,不知道说得对不对,反正我是这么理解的,说得不对的话请小伙伴们纠正
   Nsstring *carIcon = [[subElements childAtIndex:0] stringValue];
   //获取car里面的log
   Nsstring *carLog = [[subElements childAtIndex:1] stringValue];
   //获取car里面的txt
   Nsstring *carTxt = [[subElements childAtIndex:2] stringValue];
   //car里面的这个ecu就不能用childAtIndex这个方法获取了,因为我们要获取ecu里面的path和name,做法也非常简单
   NSArray *ecus = [subElements elementsForName:@"ecu"];
    DDXMLElement *ecu = [ecus firstObject];
    //获取ecu里的path,name也是同理,就懒得写了
   Nsstring *ecuPath = [[ecu attributeForName:@"path"] stringValue];
   }

这上面就是kissxml的读取xml数据的过程,还有更多功能我就懒(ye)得(bu)写(hui)了… 第一次自己写博客,大家将就看吧

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念