【问题标题】:Xerces XPath causes seg fault when path doesn't exist当路径不存在时,Xerces XPath 会导致段错误
【发布时间】:2016-01-12 20:07:24
【问题描述】:

我可以通过以下 XML 和 C++ 代码成功地使用 Xerces XPath 功能从 XML 中查询信息。

XML

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
    <ApplicationSettings>
        hello universe
    </ApplicationSettings>
</root>

C++

int main()
{
  XMLPlatformUtils::Initialize();
  // create the DOM parser
  XercesDOMParser *parser = new XercesDOMParser;
  parser->setValidationScheme(XercesDOMParser::Val_Never);
  parser->parse("fake_cmf.xml");
  // get the DOM representation
  DOMDocument *doc = parser->getDocument();
  // get the root element
  DOMElement* root = doc->getDocumentElement();

  // evaluate the xpath
  DOMXPathResult* result=doc->evaluate(
      XMLString::transcode("/root/ApplicationSettings"), // <-- HERE IS THE XPATH
      root,
      NULL,
      DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, //DOMXPathResult::ANY_UNORDERED_NODE_TYPE, //DOMXPathResult::STRING_TYPE,
      NULL);

  // look into the xpart evaluate result
  result->snapshotItem(0);
  std::cout<<TranscodeToStr(result->getNodeValue()->getFirstChild()->getNodeValue(),"ascii").str()<<std::endl;;

  XMLPlatformUtils::Terminate();
 return 0;
}

问题是有时我的 XML 将只有某些字段。但是,如果我从 XML 中删除 ApplicationSettings 条目,它将出现段错误。如何正确处理这些可选字段?我知道尝试从 seg 错误中纠正是有风险的。

【问题讨论】:

  • 您确定问题出在 Xerces 而不是您在取消引用之前忽略检查 result 的代码吗?
  • @kjhughes 我完全不确定。让我了解一下。
  • @kjhughes 好的result 不是NULL 并且包含相同的ResultType,无论XPath 是否存在,所以这部分是可以的。但是,我认为调查已经使我找到了解决方案。感谢您的建议。

标签: c++ xml xpath xerces


【解决方案1】:

此行发生段错误

 std::cout<<TranscodeToStr(result->getNodeValue()->getFirstChild()->getNodeValue(),"ascii").str()<<std::endl;

特别是在 get getFirstChild() 调用中,因为 getNodeValue() 的结果是 NULL

这是我快速而肮脏的解决方案。这不是很理想,但它确实有效。我更喜欢更复杂的评估和响应。

if (result->getNodeValue() == NULL)
{
  cout << "There is no result for the provided XPath " << endl;
}
else
{
  cout<<TranscodeToStr(result->getNodeValue()->getFirstChild()->getNodeValue(),"ascii").str()<<endl;
}

【讨论】:

    猜你喜欢
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多