本文整理汇总了C++中DOMParser::parse方法的典型用法代码示例。如果您正苦于以下问题:C++ DOMParser::parse方法的具体用法?C++ DOMParser::parse怎么用?C++ DOMParser::parse使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DOMParser
的用法示例。
在下文中一共展示了DOMParser::parse方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: confidence
/**
* Return the confidence with with this algorithm can load the file
* @param descriptor A descriptor for the file
* @returns An integer specifying the confidence level. 0 indicates it will not
* be used
*/
int LoadSpice2D::confidence(Kernel::FileDescriptor &descriptor) const {
if (descriptor.extension() != ".xml")
return 0;
std::istream &is = descriptor.data();
int confidence(0);
{ // start of inner scope
Poco::XML::InputSource src(is);
// Set up the DOM parser and parse xml file
DOMParser pParser;
Poco::AutoPtr<Document> pDoc;
try {
pDoc = pParser.parse(&src);
} catch (Poco::Exception &e) {
throw Kernel::Exception::FileError("Unable to parse File (" +
descriptor.filename() + ")",
e.displayText());
} catch (...) {
throw Kernel::Exception::FileError("Unable to parse File:",
descriptor.filename());
}
// Get pointer to root element
Element *pRootElem = pDoc->documentElement();
if (pRootElem) {
if (pRootElem->tagName() == "SPICErack") {
confidence = 80;
}
}
} // end of inner scope
return confidence;
}
示例2: confidence
/**checks the file by opening it and reading few lines
* @param filePath :: name of the file inluding its path
* @return an integer value how much this algorithm can load the file
*/
int LoadSpice2D::fileCheck(const std::string& filePath)
{
// Set up the DOM parser and parse xml file
DOMParser pParser;
Document* pDoc;
try
{
pDoc = pParser.parse(filePath);
} catch (...)
{
throw Kernel::Exception::FileError("Unable to parse File:", filePath);
}
int confidence(0);
// Get pointer to root element
Element* pRootElem = pDoc->documentElement();
if(pRootElem)
{
if(pRootElem->tagName().compare("SPICErack") == 0)
{
confidence = 80;
}
}
pDoc->release();
return confidence;
}
示例3: execManually
void LoadParameterFile::execManually(bool useString, std::string filename, std::string parameterXML, Mantid::API::ExperimentInfo_sptr localWorkspace)
{
// TODO: Refactor to remove the need for the const cast (ticket #8521)
Instrument_sptr instrument = boost::const_pointer_cast<Instrument>(localWorkspace->getInstrument()->baseInstrument());
// Set up the DOM parser and parse xml file
DOMParser pParser;
AutoPtr<Document> pDoc;
if(useString){
try
{
pDoc = pParser.parseString(parameterXML);
}
catch(Poco::Exception& exc)
{
throw Kernel::Exception::FileError (exc.displayText() + ". Unable to parse parameter XML string","ParameterXML");
}
catch(...)
{
throw Kernel::Exception::FileError("Unable to parse parameter XML string","ParameterXML");
}
}
else
{
try
{
pDoc = pParser.parse(filename);
}
catch(Poco::Exception& exc)
{
throw Kernel::Exception::FileError(exc.displayText() + ". Unable to parse File:", filename);
}
catch(...)
{
throw Kernel::Exception::FileError("Unable to parse File:" , filename);
}
}
// Get pointer to root element
Element* pRootElem = pDoc->documentElement();
if ( !pRootElem->hasChildNodes() )
{
throw Kernel::Exception::InstrumentDefinitionError("No root element in XML Parameter file", filename);
}
//
InstrumentDefinitionParser loadInstr;
loadInstr.setComponentLinks(instrument, pRootElem);
// populate parameter map of workspace
localWorkspace->populateInstrumentParameters();
}
示例4: parse
/**
* Takes a stream that is assumed to contain a single complete material
* definition,
* reads the definition and produces a new Material object. If many definitions
* are present then the first one is read
* @param istr A reference to a stream
* @return A new Material object
*/
Material MaterialXMLParser::parse(std::istream &istr) const {
using namespace Poco::XML;
typedef AutoPtr<Document> DocumentPtr;
InputSource src(istr);
DOMParser parser;
// Do not use auto here or anywhereas the Poco API returns raw pointers
// but in some circumstances requires AutoPtrs to manage the memory
DocumentPtr doc;
try {
doc = parser.parse(&src);
} catch (SAXParseException &exc) {
std::ostringstream os;
os << "MaterialXMLReader::read() - Error parsing stream as XML: "
<< exc.what();
throw std::invalid_argument(os.str());
}
Element *rootElement = doc->documentElement();
// Iterating is apparently much faster than getElementsByTagName
NodeIterator nodeIter(rootElement, NodeFilter::SHOW_ELEMENT);
Node *node = nodeIter.nextNode();
Material matr;
bool found(false);
while (node) {
if (node->nodeName() == MATERIAL_TAG) {
matr = parse(static_cast<Element *>(node));
found = true;
break;
}
node = nodeIter.nextNode();
}
if (!found) {
throw std::invalid_argument(
"MaterialXMLReader::read() - No material tags found.");
}
return matr;
}
示例5: exec
/** Executes the algorithm
*
* @throw Exception::FileError If the grouping file cannot be opened or read successfully
* @throw runtime_error If unable to run one of the Child Algorithms successfully
*/
void CreateDummyCalFile::exec()
{
// Get the input workspace
MatrixWorkspace_const_sptr inputW = getProperty("InputWorkspace");
if (!inputW)
throw std::invalid_argument("No InputWorkspace");
//Get some stuff from the input workspace
Instrument_const_sptr inst = inputW->getInstrument();
std::string instname = inst->getName();
// Check that the instrument is in store
// Get only the first 3 letters
std::string instshort=instname;
std::transform(instshort.begin(),instshort.end(),instshort.begin(),toupper);
instshort=instshort+"_Definition.xml";
// Determine the search directory for XML instrument definition files (IDFs)
std::string directoryName = Kernel::ConfigService::Instance().getInstrumentDirectory();
// Set up the DOM parser and parse xml file
DOMParser pParser;
Document* pDoc;
try
{
pDoc = pParser.parse(directoryName+instshort);
}
catch(...)
{
g_log.error("Unable to parse file " + m_filename);
throw Kernel::Exception::FileError("Unable to parse File:" , m_filename);
}
// Get pointer to root element
Element* pRootElem = pDoc->documentElement();
if ( !pRootElem->hasChildNodes() )
{
g_log.error("XML file: " + m_filename + "contains no root element.");
throw Kernel::Exception::InstrumentDefinitionError("No root element in XML instrument file", m_filename);
}
// Handle used in the singleton constructor for instrument file should append the value
// of the last-modified tag inside the file to determine if it is already in memory so that
// changes to the instrument file will cause file to be reloaded.
auto temp = instshort + pRootElem->getAttribute("last-modified");// Generate the mangled name by hand (old-style)
// If instrument not in store, insult the user
if (!API::InstrumentDataService::Instance().doesExist(temp))
{
Mantid::Geometry::IDFObject idf(directoryName+instshort);
temp = idf.getMangledName(); // new style.
if (!API::InstrumentDataService::Instance().doesExist(temp))
{
g_log.error("Instrument "+instshort+" is not present in data store.");
throw std::runtime_error("Instrument "+instshort+" is not present in data store.");
}
}
// Get the names of groups
groups=instname;
// Split the names of the group and insert in a vector, throw if group empty
std::vector<std::string> vgroups;
boost::split( vgroups, instname, boost::algorithm::detail::is_any_ofF<char>(",/*"));
if (vgroups.empty())
{
g_log.error("Could not determine group names. Group names should be separated by / or ,");
throw std::runtime_error("Could not determine group names. Group names should be separated by / or ,");
}
// Assign incremental number to each group
std::map<std::string,int> group_map;
int index=0;
for (std::vector<std::string>::const_iterator it=vgroups.begin(); it!=vgroups.end(); ++it)
group_map[(*it)]=++index;
// Not needed anymore
vgroups.clear();
// Find Detectors that belong to groups
typedef boost::shared_ptr<const Geometry::ICompAssembly> sptr_ICompAss;
typedef boost::shared_ptr<const Geometry::IComponent> sptr_IComp;
typedef boost::shared_ptr<const Geometry::IDetector> sptr_IDet;
std::queue< std::pair<sptr_ICompAss,int> > assemblies;
sptr_ICompAss current=boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(inst);
sptr_IDet currentDet;
sptr_IComp currentIComp;
sptr_ICompAss currentchild;
int top_group, child_group;
if (current.get())
{
top_group=group_map[current->getName()]; // Return 0 if not in map
assemblies.push(std::make_pair(current,top_group));
}
//.........这里部分代码省略.........
示例6: Open
/*****************************************************************************
* Open:
*****************************************************************************/
static int Open(vlc_object_t *p_obj)
{
demux_t *p_demux = (demux_t*) p_obj;
if(!p_demux->s->psz_url)
return VLC_EGENERIC;
std::string mimeType;
char *psz_mime = stream_ContentType(p_demux->s);
if(psz_mime)
{
mimeType = std::string(psz_mime);
free(psz_mime);
}
PlaylistManager *p_manager = NULL;
char *psz_logic = var_InheritString(p_obj, "adaptive-logic");
AbstractAdaptationLogic::LogicType logic = AbstractAdaptationLogic::Default;
if( psz_logic )
{
for(size_t i=0;i<ARRAY_SIZE(pi_logics); i++)
{
if(!strcmp(psz_logic, ppsz_logics_values[i]))
{
logic = pi_logics[i];
break;
}
}
free( psz_logic );
}
std::string playlisturl(p_demux->s->psz_url);
bool dashmime = DASHManager::mimeMatched(mimeType);
bool smoothmime = SmoothManager::mimeMatched(mimeType);
if(!dashmime && !smoothmime && HLSManager::isHTTPLiveStreaming(p_demux->s))
{
M3U8Parser parser;
M3U8 *p_playlist = parser.parse(VLC_OBJECT(p_demux),p_demux->s, playlisturl);
if(!p_playlist)
{
msg_Err( p_demux, "Could not parse playlist" );
return VLC_EGENERIC;
}
p_manager = new (std::nothrow) HLSManager(p_demux, p_playlist,
new (std::nothrow) HLSStreamFactory, logic);
}
else
{
/* Handle XML Based ones */
DOMParser xmlParser; /* Share that xml reader */
if(dashmime)
{
p_manager = HandleDash(p_demux, xmlParser, playlisturl, logic);
}
else if(smoothmime)
{
p_manager = HandleSmooth(p_demux, xmlParser, playlisturl, logic);
}
else
{
/* We need to probe content */
const uint8_t *p_peek;
const ssize_t i_peek = vlc_stream_Peek(p_demux->s, &p_peek, 2048);
if(i_peek > 0)
{
stream_t *peekstream = vlc_stream_MemoryNew(p_demux, const_cast<uint8_t *>(p_peek), (size_t)i_peek, true);
if(peekstream)
{
if(xmlParser.reset(peekstream) && xmlParser.parse(false))
{
if(DASHManager::isDASH(xmlParser.getRootNode()))
{
p_manager = HandleDash(p_demux, xmlParser, playlisturl, logic);
}
else if(SmoothManager::isSmoothStreaming(xmlParser.getRootNode()))
{
p_manager = HandleSmooth(p_demux, xmlParser, playlisturl, logic);
}
}
vlc_stream_Delete(peekstream);
}
}
}
}
if(!p_manager || !p_manager->start())
{
delete p_manager;
return VLC_EGENERIC;
}
p_demux->p_sys = reinterpret_cast<demux_sys_t *>(p_manager);
//.........这里部分代码省略.........
示例7: loadGroupingFromXML
/**
* Loads grouping from the XML file specified.
*
* @param filename :: XML filename to load grouping information from
* @param g :: Struct to store grouping information to
*/
void loadGroupingFromXML(const std::string& filename, Grouping& g)
{
// Set up the DOM parser and parse xml file
DOMParser pParser;
Poco::AutoPtr<Document> pDoc;
try
{
pDoc = pParser.parse(filename);
}
catch(...)
{
throw Mantid::Kernel::Exception::FileError("Unable to parse File" , filename);
}
// Get pointer to root element
Element* pRootElem = pDoc->documentElement();
if (!pRootElem->hasChildNodes())
throw Mantid::Kernel::Exception::FileError("No root element in XML grouping file" , filename);
// Parse information for groups
Poco::AutoPtr<NodeList> groups = pRootElem->getElementsByTagName("group");
if (groups->length() == 0)
throw Mantid::Kernel::Exception::FileError("No groups specified in XML grouping file" , filename);
// Resize vectors
g.groupNames.resize(groups->length());
g.groups.resize(groups->length());
for (size_t ig = 0; ig < groups->length(); ig++)
{
Element* pGroupElem = static_cast<Element*>(groups->item(static_cast<long>(ig)));
if (!pGroupElem->hasAttribute("name"))
throw Mantid::Kernel::Exception::FileError("Group element without name" , filename);
g.groupNames[ig] = pGroupElem->getAttribute("name");
Element* idlistElement = pGroupElem->getChildElement("ids");
if (!idlistElement)
throw Mantid::Kernel::Exception::FileError("Group element without <ids>" , filename);
g.groups[ig] = idlistElement->getAttribute("val");
}
// Parse information for pairs
Poco::AutoPtr<NodeList> pairs = pRootElem->getElementsByTagName("pair");
// Resize vectors
g.pairNames.resize(pairs->length());
g.pairs.resize(pairs->length());
g.pairAlphas.resize(pairs->length());
for (size_t ip = 0; ip < pairs->length(); ip++)
{
Element* pPairElem = static_cast<Element*>(pairs->item(static_cast<long>(ip)));
if ( !pPairElem->hasAttribute("name") )
throw Mantid::Kernel::Exception::FileError("Pair element without name" , filename);
g.pairNames[ip] = pPairElem->getAttribute("name");
size_t fwdGroupId, bwdGroupId; // Ids of forward/backward groups
// Try to get id of the first group
if (Element* fwdElement = pPairElem->getChildElement("forward-group"))
{
if(!fwdElement->hasAttribute("val"))
throw Mantid::Kernel::Exception::FileError("Pair forward-group without <val>" , filename);
// Find the group with the given name
auto it = std::find(g.groupNames.begin(), g.groupNames.end(), fwdElement->getAttribute("val"));
if(it == g.groupNames.end())
throw Mantid::Kernel::Exception::FileError("Pair forward-group name not recognized" , filename);
// Get index of the iterator
fwdGroupId = it - g.groupNames.begin();
}
else
{
throw Mantid::Kernel::Exception::FileError("Pair element without <forward-group>" , filename);
}
// Try to get id of the second group
if(Element* bwdElement = pPairElem->getChildElement("backward-group"))
{
if(!bwdElement->hasAttribute("val"))
throw Mantid::Kernel::Exception::FileError("Pair backward-group without <val>" , filename);
// Find the group with the given name
auto it = std::find(g.groupNames.begin(), g.groupNames.end(), bwdElement->getAttribute("val"));
if(it == g.groupNames.end())
//.........这里部分代码省略.........
示例8: b_re_sig
/// Overwrites Algorithm exec method
void LoadSpice2D::exec()
{
std::string fileName = getPropertyValue("Filename");
const double wavelength_input = getProperty("Wavelength");
const double wavelength_spread_input = getProperty("WavelengthSpread");
// Set up the DOM parser and parse xml file
DOMParser pParser;
Document* pDoc;
try
{
pDoc = pParser.parse(fileName);
} catch (...)
{
throw Kernel::Exception::FileError("Unable to parse File:", fileName);
}
// Get pointer to root element
Element* pRootElem = pDoc->documentElement();
if (!pRootElem->hasChildNodes())
{
throw Kernel::Exception::NotFoundError("No root element in Spice XML file", fileName);
}
// Read in start time
const std::string start_time = pRootElem->getAttribute("start_time");
Element* sasEntryElem = pRootElem->getChildElement("Header");
throwException(sasEntryElem, "Header", fileName);
// Read in scan title
Element* element = sasEntryElem->getChildElement("Scan_Title");
throwException(element, "Scan_Title", fileName);
std::string wsTitle = element->innerText();
// Read in instrument name
element = sasEntryElem->getChildElement("Instrument");
throwException(element, "Instrument", fileName);
std::string instrument = element->innerText();
// Read sample thickness
double sample_thickness = 0;
from_element<double>(sample_thickness, sasEntryElem, "Sample_Thickness", fileName);
double source_apert = 0.0;
from_element<double>(source_apert, sasEntryElem, "source_aperture_size", fileName);
double sample_apert = 0.0;
from_element<double>(sample_apert, sasEntryElem, "sample_aperture_size", fileName);
double source_distance = 0.0;
from_element<double>(source_distance, sasEntryElem, "source_distance", fileName);
// Read in wavelength and wavelength spread
double wavelength = 0;
double dwavelength = 0;
if ( isEmpty(wavelength_input) ) {
from_element<double>(wavelength, sasEntryElem, "wavelength", fileName);
from_element<double>(dwavelength, sasEntryElem, "wavelength_spread", fileName);
}
else
{
wavelength = wavelength_input;
dwavelength = wavelength_spread_input;
}
// Read in positions
sasEntryElem = pRootElem->getChildElement("Motor_Positions");
throwException(sasEntryElem, "Motor_Positions", fileName);
// Read in the number of guides
int nguides = 0;
from_element<int>(nguides, sasEntryElem, "nguides", fileName);
// Read in sample-detector distance in mm
double distance = 0;
from_element<double>(distance, sasEntryElem, "sample_det_dist", fileName);
distance *= 1000.0;
// Read in beam trap positions
double highest_trap = 0;
double trap_pos = 0;
from_element<double>(trap_pos, sasEntryElem, "trap_y_25mm", fileName);
double beam_trap_diam = 25.4;
from_element<double>(highest_trap, sasEntryElem, "trap_y_101mm", fileName);
if (trap_pos>highest_trap)
{
highest_trap = trap_pos;
beam_trap_diam = 101.6;
}
from_element<double>(trap_pos, sasEntryElem, "trap_y_50mm", fileName);
if (trap_pos>highest_trap)
{
highest_trap = trap_pos;
beam_trap_diam = 50.8;
}
//.........这里部分代码省略.........
示例9: LoadFromFile
//**********************************************************************************************************************
bool cSettings::LoadFromFile (const string& fileName)
{
ifstream settingsFile(fileName.c_str());
msAlertCode = acOk;
if (!settingsFile.is_open())
{
cout << "Cannot open \"" << fileName << "\" for reading." << endl;
return false;
}
InputSource settingsSrc(settingsFile);
// attempt to parse the settings file
try
{
mSettingsDoc = mSettingsParser.parse(&settingsSrc);
mSettingsRoot = mSettingsDoc->documentElement();
// check that the settings root element's name is "settings"
if (mSettingsRoot->nodeName() != "settings")
{
cout << fileName << " must contain a <settings> element as its root element." << endl;
return false;
}
Element* el = mSettingsRoot->getChildElement("logfile");
if ((!el) || (!el->hasAttribute("location")))
{
cout << "WARNING: No log file location specified in settings file. Using \"./qrap.log\"." << endl;
msLogFileName = "./qrap.log";
} else
{
msLogFileName = el->getAttribute("location");
}
QRAP_INFO("-----------Begin debug logging-----------");
// check the database element
el = mSettingsRoot->getChildElement("database");
if ((!el) || (!el->hasAttribute("host")) || (!el->hasAttribute("name")))
{
QRAP_FATAL_CODE(fileName+" must contain a <database> element with connection parameters.", acInternalError);
return false;
}
#ifndef QRAP_SERVER_EDITION
// check that the synchronisation server details are in
el = mSettingsRoot->getChildElement("syncserver");
if ((!el) || (!el->hasAttribute("host")) || (!el->hasAttribute("port")))
{
QRAP_FATAL_CODE(fileName+" must contain a <syncserver> element with connection parameters.", acInternalError);
return false;
}
#endif
// check the structure element
el = mSettingsRoot->getChildElement("structure");
if ((!el) || (!el->hasAttribute("location")))
{
QRAP_FATAL_CODE(fileName+" must contain a reference to a structure XML file.", acInternalError);
return false;
}
// open up the structure file
string structFileName = el->getAttribute("location");
ifstream structFile(structFileName.c_str());
// check that the file's open
if (!structFile.is_open())
{
QRAP_FATAL_CODE("Cannot open \""+structFileName+"\" for reading.", acFileOpenRead);
return false;
}
// create an input source
InputSource structSrc(structFile);
DOMParser structParser;
AutoPtr<Document> structDoc = structParser.parse(&structSrc);
Element* structRoot = structDoc->documentElement();
// check that the structure file contains a <structure> element
if ((!structRoot) || (structRoot->nodeName() != "structure"))
{
QRAP_FATAL_CODE(structFileName+" must contain a <structure> root element.", acParse);
return false;
}
// get the "table" children
ElementsByTagNameList* tables = dynamic_cast<ElementsByTagNameList*>(structRoot->getElementsByTagName("table"));
ElementsByTagNameList* fields, *views;
int i, tableCount, j, k, fieldCount, viewCount;
unsigned refPos;
Element* curTable, *curField, *curView;
string tableName, fieldName, temp, viewName, viewAs;
tableCount = tables->length();
if (!tableCount)
//.........这里部分代码省略.........
示例10: printf
template< typename TCtx, typename Tnode> unsigned
sample_dom( char* fname) {
TCtx* ctxp;
printf( "XML C++ DOM sample\n");
printf( "Initializing context\n");
try
{
ctxp = new TCtx();
}
catch (XmlException& e)
{
unsigned ecode = e.getCode();
printf( "Failed to initialize XML context, error %u\n", ecode);
return ecode;
}
printf("Initializing Tools Factory\n");
Factory< TCtx, Tnode>* fp;
try
{
fp = new Factory< TCtx, Tnode>( ctxp);
}
catch (FactoryException& fe)
{
unsigned ecode = fe.getCode();
printf( "Failed to create factory, error %u\n", ecode);
return ecode;
}
printf("Creating DOM parser\n");
DOMParser< TCtx, Tnode>* parserp;
try
{
parserp = fp->createDOMParser( DOMParCXml, NULL);
}
catch (FactoryException& fe1)
{
unsigned ecode = fe1.getCode();
printf( "Failed to create parser, error %u\n", ecode);
return ecode;
}
printf( "Create file source\n");
FileSource* isrcp = new FileSource( (oratext*)fname);
printf("Parsing '%s' ...\n", fname);
try
{
DocumentRef< Tnode>* docrefp = parserp->parse( isrcp);
if (docrefp == NULL)
{
printf( "NULL document\n");
return 1;
}
Tnode* np = docrefp->getDocumentElement();
if (np == NULL)
{
printf( "Empty document\n");
return 1;
}
ElementRef< Tnode> elref( (*docrefp), np);
printf("Dump the DOM tree\n");
dumpTree< Tnode>( elref);
printf("Delete the DOM tree\n");
docrefp->markToDelete();
delete docrefp;
printf("Finished\n");
}
catch (ParserException& pe)
{
unsigned ecode = pe.getCode();
printf( "Failed to parse the document, error %u\n", ecode);
return ecode;
}
return 0;
}
示例11: main
int main(int argc, char **argv)
{
bool verbose = false;
#if 0
DOMParser::ValSchemes gValScheme = DOMParser::Val_Auto;
bool gDoNamespaces = true;
bool gDoSchema = true;
bool gSchemaFullChecking = false;
bool gDoCreate = false;
#endif
MFileOperations f;
char path[1024];
f.expandPath(path, "MESA_TARGET", "runtime");
::strcat(path, "/IHE-syslog-audit-message-4.xsd");
char* schemaDef = path;
int detailLevel = 1;
MString tmp;
while (--argc > 0 && (*++argv)[0] == '-') {
switch (*(argv[0] + 1)) {
case 'l':
argc--; argv++;
if (argc < 1)
usage();
tmp = *argv;
detailLevel = tmp.intData();
break;
case 's':
argc--; argv++;
if (argc < 1)
usage();
schemaDef = *argv;
break;
case 'v':
verbose = true;
break;
default:
break;
}
}
if (argc < 1)
usage();
// Initialize the XML4C2 system
try {
XMLPlatformUtils::Initialize();
}
catch (const XMLException& e) {
cout << "Unable to initialize Xerces-c software"
<< DOMString(e.getMessage()) << endl;
return 1;
}
DOMParser *parser = new DOMParser;
parser->setValidationScheme(DOMParser::Val_Auto);
parser->setDoNamespaces(true);
parser->setDoSchema(true);
parser->setValidationSchemaFullChecking(true);
if (schemaDef != "") {
parser->setExternalNoNamespaceSchemaLocation(schemaDef);
}
DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter();
parser->setErrorHandler(errReporter);
parser->setCreateEntityReferenceNodes(false);
parser->setToCreateXMLDeclTypeNode(true);
bool errorFlag = false;
try {
parser->parse(*argv);
int count = parser->getErrorCount();
if (count > 0) {
errorFlag = true;
return 1;
}
}
catch (const XMLException& e) {
cout << "Parsing error: " << DOMString(e.getMessage()) << endl;
return 1;
}
catch (const DOM_DOMException& e) {
cout << "DOM Error: " << e.code << endl;
return 1;
}
catch (...) {
cout << "Unspecified error" << endl;
return 1;
}
DOM_Document doc = parser->getDocument();
unsigned int elementCount = doc.getElementsByTagName("*").getLength();
//.........这里部分代码省略.........
示例12: main
int main (int argC, char *argV[])
{
MemoryMonitor *staticMemMonitor = new MemoryMonitor();
// Initialize the XML4C system
try
{
XMLPlatformUtils::Initialize(XMLUni::fgXercescDefaultLocale, 0, 0, staticMemMonitor);
}
catch (const XMLException& toCatch)
{
char *msg = XMLString::transcode(toCatch.getMessage());
XERCES_STD_QUALIFIER cerr << "Error during initialization! :\n"
<< msg << XERCES_STD_QUALIFIER endl;
XMLString::release(&msg);
return 1;
}
// Check command line and extract arguments.
if (argC < 2)
{
usage();
return 1;
}
const char* xmlFile = 0;
AbstractDOMParser::ValSchemes domBuilderValScheme = AbstractDOMParser::Val_Auto;
bool doNamespaces = false;
bool doSchema = false;
bool schemaFullChecking = false;
bool doList = false;
bool errorOccurred = false;
int numReps =1;
int argInd;
for (argInd = 1; argInd < argC; argInd++)
{
// Break out on first parm not starting with a dash
if (argV[argInd][0] != '-')
break;
// Watch for special case help request
if (!strcmp(argV[argInd], "-?"))
{
usage();
return 2;
}
else if (!strncmp(argV[argInd], "-v=", 3)
|| !strncmp(argV[argInd], "-V=", 3))
{
const char* const parm = &argV[argInd][3];
if (!strcmp(parm, "never"))
domBuilderValScheme = AbstractDOMParser::Val_Never;
else if (!strcmp(parm, "auto"))
domBuilderValScheme = AbstractDOMParser::Val_Auto;
else if (!strcmp(parm, "always"))
domBuilderValScheme = AbstractDOMParser::Val_Always;
else
{
XERCES_STD_QUALIFIER cerr << "Unknown -v= value: " << parm << XERCES_STD_QUALIFIER endl;
return 2;
}
}
else if (!strcmp(argV[argInd], "-n")
|| !strcmp(argV[argInd], "-N"))
{
doNamespaces = true;
}
else if (!strcmp(argV[argInd], "-s")
|| !strcmp(argV[argInd], "-S"))
{
doSchema = true;
}
else if (!strcmp(argV[argInd], "-f")
|| !strcmp(argV[argInd], "-F"))
{
schemaFullChecking = true;
}
else if (!strcmp(argV[argInd], "-l")
|| !strcmp(argV[argInd], "-L"))
{
doList = true;
}
else if (!strncmp(argV[argInd], "-r=", 3)
|| !strncmp(argV[argInd], "-R=", 3))
{
const char* const numStr = &argV[argInd][3];
XMLCh* numXStr = XMLString::transcode(numStr);
numReps = XMLString::parseInt(numXStr);
XMLString::release(&numXStr);
}
else
{
XERCES_STD_QUALIFIER cerr << "Unknown option '" << argV[argInd]
<< "', ignoring it\n" << XERCES_STD_QUALIFIER endl;
}
}
//.........这里部分代码省略.........