我正在尝试使用Xerces-C ++解析XML文档。我只是想通过它的id搜索一个元素。我写了以下代码,但它不起作用。 ...
try {
XMLPlatformUtils::Initialize();
}
catch(XMLException& e) {
char* message = XMLString::transcode( e.getMessage() );
cout << "XML toolkit initialization error: " << message << endl;
XMLString::release( &message );
}
XMLCh tempStr[100];
XMLString::transcode("LS", tempStr, 99);
DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
DOMLSParser* parser = ((DOMImplementationLS*)impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, 0);
char *filename = "C:\\odx1.xml";
xercesc::DOMDocument *doc = 0;
try {
doc = parser->parseURI(filename);
DOMElement *element = doc->getElementById(XMLString::transcode("test"));
if(element != NULL) cout << "element found";
cout << "DONE";
}
catch (const XMLException& toCatch) {
char* message = XMLString::transcode(toCatch.getMessage());
cout << "Exception message is: \n"
<< message << "\n";
XMLString::release(&message);
return;
}
catch (const DOMException& toCatch) {
char* message = XMLString::transcode(toCatch.msg);
cout << "Exception message is: \n"
<< message << "\n";
XMLString::release(&message);
return;
}
catch (...) {
cout << "Unexpected Exception \n" ;
return ;
}
parser->release();
XMLPlatformUtils::Terminate();
}
...
XML是:
<ODX MODEL-VERSION="2.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="odx.xsd">
<DIAG-LAYER-CONTAINER ID="test">
test done
</DIAG-LAYER-CONTAINER>
</ODX>
我希望它能打印出“找到的元素”,但程序会正确终止,而不会打印“找到元素”。
无论如何......在与XML文档关联的XSD文件中,我正在搜索的元素有<xsd:attribute name="ID" type="xsd:ID" use="required"/>
所以我希望元素由getElementById返回。
答案 0 :(得分:3)
请查看this
返回ID由elementId指定的DOMElement。如果没有这样的话 元素存在,返回null。如果不止一个,则不定义行为 element有此ID。 DOM实现必须具有信息 说哪个属性是ID类型。具有名称的属性 除非如此定义,否则“ID”不是ID类型。没有的实现 知道属性是否属于ID类型,预计会返回 空。
也许你可以通过其他方式获得元素?作为标签名称?
答案 1 :(得分:2)
解决方案是:
XMLCh tempStr[100];
XMLString::transcode("LS", tempStr, 99);
DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(tempStr);
DOMLSParser* parser = ((DOMImplementationLS*)impl)->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, 0);
DOMConfiguration* conf = parser->getDomConfig ();
conf->setParameter(XMLUni::fgXercesSchema, true);
char *filename = "C:\\odx1.xml";
xercesc::DOMDocument *doc = 0;
try {
doc = parser->parseURI(filename);
DOMElement *element = doc->getElementById(XMLString::transcode("test"));
if(element != NULL) cout << "element found";
cout << "DONE";
}