简体   繁体   English

类似于libxml2中selectSingleNode的功能?

[英]Similar function to selectSingleNode in Libxml2?

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
<catalog>

IXMLDOMNode* pnode;
IXMLDOMNode* pNodeAuthor = NULL;
pnode->selectSingleNode (CComBSTR(L"author"), & pNodeAuthor);

OR 要么

getElementsByTagName("book[@id='bk101']") 

OR 要么

selectNodes("//book[@id='bk101']") 

Q: In the above XML file, using Microsoft's XML DOM I am able to get any specific node by using selectSingleNode() or getElementbyTagName() or selectNodes() function, just by passing the node name. 问:在上面的XML文件中,使用Microsoft的XML DOM,我可以通过使用selectSingleNode()或getElementbyTagName()或selectNodes()函数来获取任何特定节点,只需传递节点名称即可。

I want to do the same using Libxml2, I've read all the standard functions, but not getting any function like that, if you know any function similar or the other way to do that then Please Help! 我想用Libxml2做同样的事情,我已经阅读了所有的标准函数,但没有得到任何类似的函数,如果你知道任何类似的功能或其他方法那么请帮忙!

It's a lot of time I don't use libxml2 but... 很多时候我不使用libxml2但是......

There are more ways to do it. 有更多方法可以做到这一点。 One way is using xpath 一种方法是使用xpath

Here it's an example 是一个例子

Briefly, first of all you should open and parse the xml file, obtaining an xmlDocPtr with xmlParseFile() 简而言之,首先你应该打开并解析xml文件,用xmlParseFile()获取xmlDocPtr

xmlDocPtr xmlDoc = xmlParseFile(fileName);

Next, you should create an xml-path context with xmlXPathNewContext() 接下来,您应该使用xmlXPathNewContext()创建一个xml-path上下文

xmlXPathContextPtr  xPathCnt = xmlXPathNewContext(xmlDoc);

Now you can find nodes with xpath rules; 现在您可以找到具有xpath规则的节点; in your case 在你的情况下

xmlXPathObjectPtr result = xmlXPathEvalExpression((xmlChar*)"//book[@id=\'bk101\']", xPathCnt);

If the result isn't empy, and you can check this with 如果结果不合适,您可以查看

xmlXPathNodeSetIsEmpty(result->nodesetval)

your elements should be in result->nodessetval and they number should be result->nodessetval->nodeNr 你的元素应该在result->nodessetval ,它们的编号应该是result->nodessetval->nodeNr

More details in the linked example. 链接示例中的更多详细信息。

ps: caution, code not tested ps:谨慎,代码未经过测试

ps2: sorry for my bad English ps2:抱歉我的英语不好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM