3

私はかなりの量の XML を Perl で作成しましたが、今はプロジェクトのために ANDI C で作成する必要があります。XML のスニペットを使用して作成したコードを次に示します。私はある程度成功しましたが、兄弟を得るのに問題があります。それはとても簡単だと確信していますが、私はそれを得ることができません. 2 つの関数があり、1 つはノード セットを取得するだけです (xmlsoft.org から直接コピーされます)。2番目の機能は私のものです。

xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath){

    xmlXPathContextPtr context;
    xmlXPathObjectPtr result;

    context = xmlXPathNewContext(doc);
    if (context == NULL) {
        printf("Error in xmlXPathNewContext\n");
        return NULL;
    }

    result = xmlXPathEvalExpression(xpath, context);
    xmlXPathFreeContext(context);

    if (result == NULL) {
        printf("Error in xmlXPathEvalExpression\n");
        return NULL;
    }

    if(xmlXPathNodeSetIsEmpty(result->nodesetval)){
        xmlXPathFreeObject(result);
                printf("No result\n");
        return NULL;
    }

    return result;
}

    void reader(xmlDocPtr xmlDoc, char *xpath)
{

    xmlXPathObjectPtr xpathresult;
    xmlNodeSetPtr node;
    xmlNodeSetPtr node2;
    xmlChar *title;

    int cnt;

    // parse feed in memory to xml object
    doc = xmlReadMemory(xmlDoc,strlen(xmlDoc),"noname.xml",NULL,0);

    if (!doc) criterr("Error parsing xml document");

    // get xpath node set (ttn retrieves the value from the token table)
    xpathresult = getnodeset(doc, ( xmlChar * ) xpath);

    if (xpathresult) {
        node = xpathresult->nodesetval;
        printf("Content-type: text/html\n\n");

        for (cnt=0;cnt<node->nodeNr; cnt++) {

            title = xmlNodeListGetString(doc, node->nodeTab[cnt]->xmlChildrenNode,1);

            printf("%d) title= %s<br/>\n",cnt,title);
            xmlFree(title);         
        }

        xmlXPathFreeObject(xpathresult);
        xmlFreeDoc(doc);
        xmlCleanupParser();

    } else {
        criterr("Xpath failed");
    }

    xmlFreeDoc(doc);

    criterr("Success");
}

および xml スニペット

<item>
  <title>this is the title</title>
  <link>this is the link</link>
  <description>this is the description</description>
</item>

すべてのタイトルを取得するよう//item/titleに XPath を使用すると、アイテムを取得してから node->nodeNr ループで、タイトル、リンク、および説明を簡単に取得できるようにする必要があります。 'ブロック、そのブロックの子または兄弟を簡単に取得する方法がわかりません。

4

1 に答える 1

4

を使用しxmlNextElementSiblingます。どのようにそれを見つけるのですか?Tree APIに移動し、兄弟を検索します。

そして、これはあなたのループであり、リンクも取得しています。

    for (cnt=0;cnt<node->nodeNr; cnt++) {
        xmlNodePtr titleNode = node->nodeTab[cnt];
        // titleNode->next gives empty text element, so better:
        xmlNodePtr linkNode = xmlNextElementSibling(titleNode);

        title = xmlNodeListGetString(doc, titleNode->xmlChildrenNode,1);
        link = xmlNodeListGetString(doc, linkNode->xmlChildrenNode,1);

        printf("%d) title= %s<br/>, link=%s\n",cnt,title,link);
        xmlFree(title);         
        xmlFree(link);
    }

titleNode->nextリンクを指すようにすることもできます。libxml2でこれらのXML要素を取得する方法を参照してください。

そして子供を得る?xmlFirstElementChildそして、whileをループしnode->nextます。

于 2012-09-22T06:54:27.030 に答える