XERCES-CのXPathサポート
質問
XML解析にXerces-Cを使用するレガシーC ++アプリケーションをサポートしています。私は.NETに甘やかされており、XPathを使用してDOMツリーからノードを選択することに慣れています。
Xerces-Cで限られたXpath機能にアクセスする方法はありますか? selectnodes( "/for/bar/baz")のようなものを探しています。私はこれを手動で行うことができましたが、Xpathは比較するととてもいいです。
解決
Xerces FAQを参照してください。
http://xerces.apache.org/xerces-c/faq-other-2.html#faq-9
Xerces-C ++はXpathをサポートしますか? No.Xerces-C ++ 2.8.0およびXERCES-C ++ 3.0.1は、スキーマのアイデンティティの制約を処理するための部分的なXPath実装のみを備えています。完全なXPathサポートについては、Apache Xalan C ++またはPathanのような他のオープンソースプロジェクトを参照できます。
ただし、Xalanを使用してやりたいことをするのはかなり簡単です。
他のヒント
以下は、XPath評価の実用的な例です Xerces3.1.2.
サンプルXML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<ApplicationSettings>hello world</ApplicationSettings>
</root>
C ++
#include <iostream>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/util/TransService.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
using namespace xercesc;
using namespace std;
int main()
{
XMLPlatformUtils::Initialize();
// create the DOM parser
XercesDOMParser *parser = new XercesDOMParser;
parser->setValidationScheme(XercesDOMParser::Val_Never);
parser->parse("sample.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"),
root,
NULL,
DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
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;
}
XMLPlatformUtils::Terminate();
return 0;
}
コンパイルして実行します (標準のXercesライブラリのインストールとC ++ファイルという名前を想定しています xpath.cpp)
g++ -g -Wall -pedantic -L/opt/lib -I/opt/include -DMAIN_TEST xpath.cpp -o xpath -lxerces-c
./xpath
結果
hello world
による よくある質問, 、Xerces-Cは部分的なXPath 1の実装をサポートしています。
同じエンジンがdomdocument :: evaluate apiを介して利用可能になります。ユーザーは、述語テストなしでドメレメントノードのみを含む単純なxpathクエリを実行し、「//」演算子を初期ステップとしてのみ許可します。
あなたが使う domdocument :: evaluate() 式を評価するには、aを返します domxpathResult.