首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用XPath搜索QDomDocument中的节点

使用XPath搜索QDomDocument中的节点
EN

Stack Overflow用户
提问于 2019-05-09 22:45:23
回答 1查看 1.2K关注 0票数 2

我被System.Xml名称空间中的C#及其XML操作类宠坏了(当然是坏了)。我可以将XML文件加载到XmlDocument中。我可以使用XmlNode.SelectNodes( "an xpath expression" )在整个文档中搜索与XPath表达式匹配的节点。结果是一个包含我可以遍历的XmlNode对象的XmlNodeList

现在我使用的是C++ Qt (版本4.7.1和4.8,但具体的版本可能并不重要)。我可以将XML文件加载到QDomDocument中。但是,令我沮丧的是,我不能像在C#中那样使用XPath表达式搜索文档。

我使用QXmlQuery在XML文件中查找内容的成功有限。如果我以正确的方式编写查询,我可以获得结果的QStringList,迭代该QStringList,然后将数据存储在某个地方供以后使用。

但是,我仍然希望能够直接通过XPath表达式获得文档中的QDomNode对象集合。一个特定的用例是找到一个"name“属性具有特定值的元素,然后用一个新元素替换该元素。这就是为什么我想要QDomNode对象本身,而不仅仅是QXmlQuery可以提供的一些基于字符串的表示或其他表示。对于刚才提到的特定用例,我使用QDomElement.elementsByTagName()并迭代这些元素,但它不像XPath那样灵活,也不像case那样酷。

这只是痴心妄想吗?开发一些实现QAbstractXmlReceiver接口的新类是否值得呢?或者,我最终会得到一个与QDomDocument中的QDomNode对象没有直接关系的新数据集合吗

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-16 06:04:04

下面是我用来通过XPath表达式在QDomDocument中搜索节点的实用函数。它使用@Alejandro建议的QDomNodeModel类,可从https://adared.ch/qdomnodemodel-qxmlquery下载。它基于https://www.qtcentre.org/threads/37645-QAbstractXmlNodeModel-implementation-QDomNodeModel-QXmlQuery中的用法示例。感谢Stanislaw Adaszewski,他提供了QDomNodeModel类和用法示例。

QDomNodeModel中有一些方法被注释为未实现。但是,对于我需要搜索的简单XML内容,QDomNodeModel就足够了。

代码语言:javascript
复制
//
/// @brief Search for nodes in a QDomDocument using an XPath.
/// @note I cannot return a QDomNodeList, because it has no public methods for adding items to it.
/// @param[in] doc The document to search.
/// @param[in] fromNode The node in the document to start searching from.
///   e.g., to search the whole document, use <code>doc.documentElement()</code>.
/// @param[in] xpath The XPath expression.
/// @return A list of found nodes.
//
QList<QDomNode> findNodes( QDomDocument const & doc, QDomNode const & fromNode, QString const & xpath )
{
  qDebug( "%s", __FUNCTION__ );
  QList<QDomNode> foundNodes;

  //------------------------------
  // The name pool that everybody shares.
  QXmlNamePool pool;

  //------------------------------
  // The model that wraps the document.
  QDomNodeModel model( pool, doc );

  //------------------------------
  // The query.
  // XQuery10 means the default XQuery 1.0 language, as opposed to XSLT20.
  QXmlQuery query( /*QXmlQuery::XQuery10,*/ pool );

  // Operate on the given node.
  QXmlNodeModelIndex fromIndex = model.fromDomNode( fromNode );
  query.setFocus( QXmlItem( fromIndex ) );

  // The query statement.
  query.setQuery( xpath );
  if ( !query.isValid() )
  {
    qDebug( "Query is not valid" );
    return foundNodes;
  }

  //------------------------------
  // The destination for the result of the query.
  QXmlResultItems result;

  //------------------------------
  // Evaluate the query.
  query.evaluateTo( &result );
  if ( result.hasError() )
  {
    qDebug( "Query evaluation failed" );
    return foundNodes;
  }

  //------------------------------
  // The result of the query.
  qDebug( "Query result:" );
  while ( !result.next().isNull() )
  {
    QXmlNodeModelIndex index = result.current().toNodeModelIndex();
    QDomNode node = model.toDomNode( index );
    qDebug( "  %d %s: %s", node.nodeType(), qPrintable( node.nodeName() ), qPrintable( node.nodeValue() ) );
    foundNodes << node;
  }

  return foundNodes;
}

在我的应用程序中,我加载了一个XML文件,并使用上面的实用程序函数对其进行搜索。

代码语言:javascript
复制
//------------------------------
// The path of the XML file.
QString path = "settings.xml";

//------------------------------
// Open the file.
QFile file( path );
if ( !file.open( QIODevice::ReadOnly ) )
{
  qDebug( "Failed to open '%s': %s", qPrintable( path ), qPrintable( file.errorString() ) );
  return;
}

//------------------------------
// Load the file into a document.
QDomDocument doc;
QString error;
int line;
int column;
if ( !doc.setContent( &file, &error, &line, &column ) )
{
  qDebug( "%s(%d,%d): %s", qPrintable( path ), line, column, qPrintable( error ) );
  return;
}

//------------------------------
// The document root element.
QDomElement rootElem = doc.documentElement();

//------------------------------
// Search for an element whose name attribute has a certain value.
QString name = "Alice";
QString xpath = QString( "setting[@name='%1']" ).arg( name );
QList<QDomNode> foundNodes = findNodes( doc, rootElem, xpath );

//------------------------------
// Did I find it?
if ( foundNodes.size() > 0 )
{
  QDomElement foundElem = foundNodes.at( 0 ).toElement();

  // Do something with that element.      
  ...
} 

要搜索的示例XML内容。

代码语言:javascript
复制
<?xml version='1.0'?>
<settings>
  <setting name="Bob">12</setting>
  <setting name="Carol">34</setting>
  <setting name="Ted">56</setting>
  <setting name="Alice">78</setting>
</settings>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56062025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档