我想使用Xerces-C++解析XML文档。我只是希望能够通过它的id来搜索元素。我写了下面的代码,但它不起作用。 ...无法使用Xerces-C++解析XML
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返回。
你能还添加XML? – 2013-03-15 14:34:19
如果你想得到一些帮助,“它不起作用”是不够的信息。你的代码产生了什么,你期望它产生了什么? – undu 2013-03-15 14:34:24
XSD文件如何与XML文档关联?也许你在XML文件中使用'schemaLocation'?或者,您也可以在软件中指定模式(请参阅http://codesynthesis.com/~boris/blog/2010/03/15/validating-external-schemas-xerces-cxx/) – 2013-03-19 15:10:06