objective C - 如何使用libxml2从xml解析递归节点

时间:2011-12-08 19:44:38

标签: iphone objective-c xml-parsing libxml2

下面是带有递归元素的XML:

<Tree>
    <Node name="books" label="books">
        <Node name="Maths" label="Maths">
            <Node name="Topic 1" label="Topic 1">
                <Node name="chapter 1" label="chapter 1"/>
                <Node name="chapter 2" label="chapter 2"/>
                <Node name="chapter 3" label="chapter 3"/>
                <Node name="chapter 4" label="chapter 4"/>
                <Node name="chapter 5" label="chapter 5"/>
            </Node>
        </Node>
        <Node name="Physics" label="Physics">
            <Node name="Topic 1" label="Topic 1">
                <Node name="chapter 1" label="chapter 1"/>
                <Node name="chapter 2" label="chapter 2"/>
                <Node name="chapter 3" label="chapter 3"/>
            </Node>
        </Node>
    </Node>
    <Node name="Pens" label="Pens">
    </Node>
</Tree>

ħ

我尝试使用以下代码获取递归值,但我可以获得第一级属性,但无法获得第二级“Node”元素属性值,

-(void)parse
{
        NSString *strVal = [[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];

    xmlDoc * doc = xmlParseMemory(xmlData.bytes, xmlData.length);
    xmlNodePtr nodePtr =xmlDocGetRootElement(doc);
    nodePtr = nodePtr->xmlChildrenNode;
    getChild(nodePtr, (xmlChar *)"Node");

}


int recursive = 0;
void getChild(xmlNodePtr nodePtr, xmlChar *elementName)
{
    NSLog(@"recursive: %d",recursive ++);
    xmlNodePtr tempPtr = nodePtr;

    while (tempPtr!= NULL) {
        if (!xmlStrcmp(tempPtr->name, elementName)) {
            xmlChar *v = xmlGetProp(tempPtr, (const xmlChar *)"name");
            NSLog(@"element:%s field:%s val: %s",elementName, "name", v);
           // nodePtr = nodePtr->next;
        }
        tempPtr = tempPtr -> next;
    }
    xmlNodePtr nodePtr2 = nodePtr -> xmlChildrenNode;
    getChild(nodePtr2, elementName);
}

结果是:

2011-12-09 01:12:12.271 LibXMLParser [4123:207]递归:0  2011-12-09 01:12:12.275 LibXMLParser [4123:207]元素:SystemNode字段:名称val:MSG  2011-12-09 01:12:12.276 LibXMLParser [4123:207]元素:SystemNode字段:名称val:SAP  2011-12-09 01:12:12.277 LibXMLParser [4123:207]递归:1

任何人都可以给我答案如何从根目录中递归获取节点的子节点吗?

提前致谢

0 个答案:

没有答案