📅  最后修改于: 2023-12-03 15:13:26.615000             🧑  作者: Mango
Apache Xerces是Apache Software Foundation下的一个XML解析器,提供了Java和C++两种版本,分别叫做Xerces-J和Xerces-C。
./configure && make
命令,编译生成静态库;使用Java环境的Xerces-J解析XML文件:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class XmlParser {
public static void main(String[] args) throws SAXException, IOException {
URL xmlUrl = new URL("http://www.w3.org/TR/1998/REC-xml-19980210");
InputStream xmlStream = xmlUrl.openStream();
DOMParser parser = new DOMParser();
parser.parse(xmlStream);
Document doc = parser.getDocument();
System.out.println(doc.getFirstChild().getNodeName());
}
}
使用C++环境的Xerces-C解析XML文件:
#include <string>
#include <iostream>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/dom/DOMTreeWalker.hpp>
#include <xercesc/dom/DOMXPathResult.hpp>
#include <xercesc/framework/LocalFileFormatTarget.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/util/PlatformUtils.hpp>
int main(int argc, char **argv) {
try {
XMLPlatformUtils::Initialize();
XercesDOMParser parser;
parser.setValidationScheme(XercesDOMParser::Val_Never);
parser.parse("test.xml");
DOMDocument* doc = parser.getDocument();
std::string xpath = "//items/item[name='product2']/price";
XMLCh *wstr = XMLString::transcode(xpath.c_str());
DOMXPathResult *result = doc->evaluate(wstr, doc, NULL,
DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE, NULL);
std::cout << result->getNodeValue()->getFirstChild()->getNodeValue() << std::endl;
} catch (const XMLException& e) {
std::cerr << "Error: " << e.getMessage() << std::endl;
return 1;
} catch (...) {
std::cerr << "Unexpected Error" << std::endl;
return 1;
}
XMLPlatformUtils::Terminate();
return 0;
}