私はかなりの量の 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 ループで、タイトル、リンク、および説明を簡単に取得できるようにする必要があります。 'ブロック、そのブロックの子または兄弟を簡単に取得する方法がわかりません。