首页 > 代码库 > iOS TBXML的使用

iOS TBXML的使用

解析XML/JSON都要事先了解XML/JSON的结构,对于手机来说可能用JSON更轻量级,但是用Java做服务端的话可能更倾向于使用XML,一下介绍TBXML官方示例。

<?xml version="1.0"?><authors>    <author name="J.K. Rowling">        <book title="Harry Potter and the Philosopher‘s Stone" price="119.99">            <description>                Harry potter thinks he is an ordinary boy - until he is rescued from a beetle-eyed giant of a man, enrolls at Hogwarts School of Witchcraft and Wizardry, learns to play quidditch and does battle in a deadly duel.            </description>        </book>        <book title="Harry Potter and the Chamber of Secrets" price="8.99">            <description>                When the Chamber of Secrets is opened again at the Hogwarts School for Witchcraft and Wizardry, second-year student Harry Potter finds himself in danger from a dark power that has once more been released on the school.            </description>        </book>    </author>    <author name="Douglas Adams">        <book title="The Hitchhiker‘s Guide to the Galaxy" price="15.49">            <description>                Join Douglas Adams‘s hapless hero Arthur Dent as he travels the galaxy with his intrepid pal Ford Prefect, getting into horrible messes and generally wreaking hilarious havoc.            </description>        </book>        <book title="The Restaurant at the End of the Universe " price="14.36">            <description>                Arthur and Ford, having survived the destruction of Earth by surreptitiously hitching a ride on a Vogon constructor ship, have been kicked off that ship by its commander. Now they find themselves aboard a stolen Improbability Drive ship commanded by Beeblebrox, ex-president of the Imperial Galactic Government and full-time thief.            </description>        </book>    </author></authors>

 主要的数据结构有

typedef struct _TBXMLElement {char * name;char * text;TBXMLAttribute * firstAttribute;struct _TBXMLElement * parentElement;struct _TBXMLElement * firstChild;struct _TBXMLElement * currentChild;struct _TBXMLElement * nextSibling;struct _TBXMLElement * previousSibling;} TBXMLElement;
typedef struct _TBXMLAttribute {char * name;char * value;struct _TBXMLAttribute * next;} TBXMLAttribute;

读取一个XML文件或从XML字符串或从NSData读取方式为

TBXML *tbxml = [[TBXML alloc] initWithXMLFile:@"books.xml"];TBXML *tbxml = [[TBXML alloc] initWithXMLFile:@"books" fileExtension:@"xml"];TBXML *tbxml = [[TBXML alloc] initWithXMLString:xmlString];TBXML *tbxml = [[TBXML alloc] initWithXMLData:xmlData];