XML遍历解析-TBXML的使用

假设一段xml:

///xmlStr
/*
<A>
    <B>
        <C id='c1'>C1</C>
        <C>C2</C>
        <C>C3</C>
        <C>C4</C>
    </B>
    <B>
        <C id='c2'>C5</C>
        <C>C6</C>
        <C>C7</C>
    </B>
</A>
*/

解析出C1-C7的数组:

    NSMutableArray *m_dict = [NSMutableArray array];
    NSString *xmlString = @"<A><B><C id='c1'>C1</C><C>C2</C><C>C3</C><C>C4</C></B><B><C id='c2'>C5</C><C>C6</C><C>C7</C></B></A>";
    TBXML *XML = [TBXML newTBXMLWithXMLString:xmlString error:nil];
    TBXMLElement *root = XML.rootXMLElement;
    
    TBXMLElement *elementB = [TBXML childElementNamed:@"B" parentElement:root];
    while (elementB) {
        TBXMLElement *elementC = [TBXML childElementNamed:@"C" parentElement:elementB];
        while (elementC) {
            [m_dict addObject:[TBXML textForElement:elementC]];
            elementC = [TBXML nextSiblingNamed:@"C" searchFromElement:elementC];
        }
        elementB = [TBXML nextSiblingNamed:@"B" searchFromElement:elementB];
    }
    
    for (NSString *s in m_dict) {
        NSLog(@"%@",s);
    }

输出:

C1-C7

你可能感兴趣的:(xml)