【问题标题】:Is it possible to get element text using POCO XPath是否可以使用 POCO XPath 获取元素文本
【发布时间】:2016-08-26 09:57:31
【问题描述】:

XML:

<root>
  <headers>
          <aaa>111</aaa>
          <bbb>222</bbb> 
  </headers>
</root>

我尝试过的一些 xpath(未找到或值为空):

/root/headers/bbb value[]       
/root/headers/aaa value[]       
/root/headers/bbb/text() could not be found.        
/root/headers/aaa/text() could not be found.        
//bbb value[]           
//bbb/text() could not be found.            
//bbb[1] could not be found.        
//aaa[0] value[]        
/root/headers/bbb[1] could not be found.        
/root/headers/aaa[0] value[]    

代码:

Poco::XML::XMLString xmlPath(xPath);
Poco::XML::Node* node = rootNode->getNodeByPath(xmlPath);
std::string value = node->nodeValue();

是否可以使用 XPath 获得 111 或 222 个值?

【问题讨论】:

  • 你试过/root/headers/bbb/text()[1]吗?
  • @PeterK 我确实尝试过 /root/headers/bbb/text()[1] 或 /root/headers/bbb/text()[0] - 没有运气。

标签: c++ xml xpath poco poco-libraries


【解决方案1】:

给你:

//root//headers//text()

【讨论】:

    【解决方案2】:
    std::string value;
    Poco::XML::Node* node = rootNode->getNodeByPath("//aaa"); // the Node is the Element aaa
    if (node && node->firstChild() && node->firstChild()->nodeType() == Poco::XML::Node::TEXT_NODE)
        value = node->firstChild()->nodeValue(); // firstChild of the Element is the Text node, nodeValue() give its text (you should also Poco::trim() it)
    
    // same for "//bbb"
    

    【讨论】:

    • 我想知道为什么有人投票支持我的第一个答案没有用,而这是完成所需操作的唯一方法:使用 Poco 获取元素内的文本(这不会支持 XPath,但获取元素节点或属性值的语法更简单),您必须获取元素的第一个子节点(预期为文本节点)。我有同样的问题并找到了这个答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 2013-01-15
    • 1970-01-01
    相关资源
    最近更新 更多