libxml2 xpath namespace

51 篇文章 0 订阅
40 篇文章 2 订阅

使用libxml2的xpath进行节点查询时。在测试中十分正常。后来在应用中发现总是无法找到结果。返回结果数为空。

对比测试文件与系统生成xml文件发现关于xmlns属性变化引起异常。

当使用无prefix命名空间时,会引起此异常xmlns="http://www..com.cn/xxx.xsd"

百度N个网页后找到替代方案"//*[local-name()='UserTag'][@name=\'%s\']"

即在//*[local-name()='UserTag']中UserTag为节点名称@name=\'%s\'为属性name值

可以使用libxml2库的xpath功能来修改节点的值。以下是一个示例代码: ```c #include <stdio.h> #include <libxml/parser.h> #include <libxml/xpath.h> int main(void) { xmlDocPtr doc; xmlXPathContextPtr xpathCtx; xmlXPathObjectPtr xpathObj; xmlNodePtr node; const xmlChar *xpathExpr = (const xmlChar *)"//book[author='Charles Dickens']/title"; const xmlChar *new_value = (const xmlChar *)"A Tale of Two Cities"; // Load the XML document doc = xmlReadFile("books.xml", NULL, 0); if (doc == NULL) { fprintf(stderr, "Failed to parse document\n"); return 1; } // Create an XPath context xpathCtx = xmlXPathNewContext(doc); if (xpathCtx == NULL) { fprintf(stderr, "Failed to create XPath context\n"); xmlFreeDoc(doc); return 1; } // Evaluate the XPath expression xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx); if (xpathObj == NULL) { fprintf(stderr, "Failed to evaluate XPath expression\n"); xmlXPathFreeContext(xpathCtx); xmlFreeDoc(doc); return 1; } // Get the first matching node node = xpathObj->nodesetval->nodeTab[0]; // Change the node value xmlNodeSetContent(node, new_value); // Save the modified document if (xmlSaveFile("books.xml", doc) < 0) { fprintf(stderr, "Failed to save document\n"); xmlXPathFreeObject(xpathObj); xmlXPathFreeContext(xpathCtx); xmlFreeDoc(doc); return 1; } // Cleanup xmlXPathFreeObject(xpathObj); xmlXPathFreeContext(xpathCtx); xmlFreeDoc(doc); return 0; } ``` 这个示例代码会在books.xml文件中找到作者为Charles Dickens的书的标题,并将其修改为"A Tale of Two Cities"。要使用此代码,需要将books.xml文件放在与代码相同的目录下,并且需要链接libxml2库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值