CARMA C++
DOMUtils.h
1 /*
2  * Xerces-C DOM Utilities
3  *
4  * Copyright (c) 2010 Ira W. Snyder <iws@ovro.caltech.edu>
5  */
6 
7 #ifndef DOMUTILS_H
8 #define DOMUTILS_H
9 
10 #include <algorithm>
11 #include <sstream>
12 #include <xercesc/dom/DOM.hpp>
13 
15 #include <carma/util/xercesUtils.h>
16 
17 /*----------------------------------------------------------------------------*/
18 /* Fault System Helper Functions */
19 /*----------------------------------------------------------------------------*/
20 
21 /* Is this the empty string */
22 inline bool isEmpty(const std::string &s)
23 {
24  if (s.find_first_not_of(" \t\n\r") != std::string::npos)
25  return false;
26 
27  return true;
28 }
29 
30 inline std::string getAttributeAsString(const xercesc::DOMElement *elem, const std::string &attr)
31 {
32  carma::util::AutoXMLString attrStr(attr);
33  carma::util::AutoXMLString valueStr(elem->getAttribute(attrStr.asXMLString()));
34 
35  return valueStr.getString();
36 }
37 
38 inline unsigned int getAttributeAsInt(const xercesc::DOMElement *elem, const std::string &attr)
39 {
40  carma::util::AutoXMLString attrStr(attr);
41  carma::util::AutoXMLString valueStr(elem->getAttribute(attrStr.asXMLString()));
42  std::istringstream iss;
43  unsigned int num;
44 
45  iss.str(valueStr.getString());
46  if (!(iss >> num)) {
47  std::ostringstream oss;
48 
49  oss << "could not parse \"" << valueStr.getString() << "\" as an int";
50  throw CARMA_ERROR(oss.str());
51  }
52 
53  return num;
54 }
55 
56 inline bool getAttributeAsBool(const xercesc::DOMElement *elem, const std::string &attr)
57 {
58  carma::util::AutoXMLString attrStr(attr);
59  carma::util::AutoXMLString valueStr(elem->getAttribute(attrStr.asXMLString()));
60  std::string s = valueStr.getString();
61 
62  /* lowercase the string */
63  std::transform(s.begin(), s.end(), s.begin(), ::tolower);
64 
65  if (s == "true")
66  return true;
67 
68  if (s == "false")
69  return false;
70 
71  /* error */
72  std::ostringstream oss;
73  oss << "could not parse \"" << valueStr.getString() << "\" as a bool";
74  throw CARMA_ERROR(oss.str());
75 }
76 
77 inline bool isNodeType(const xercesc::DOMNode *node, const std::string &tag)
78 {
79  if (!node)
80  return false;
81 
82  if (node->getNodeType() != xercesc::DOMNode::ELEMENT_NODE)
83  return false;
84 
85  const xercesc::DOMElement *elem = dynamic_cast<const xercesc::DOMElement *>(node);
86  if (!elem)
87  return false;
88 
89  carma::util::AutoXMLString elemTag(elem->getTagName());
90  if (elemTag.getString() != tag)
91  return false;
92 
93  return true;
94 }
95 
96 #endif /* DOMUTILS_H */
Exception class for errors.
auto cleanup class for xercesc::XMLString instances
Definition: xercesUtils.h:47
#define CARMA_ERROR(y)
Trick to get the file name and line number passed to the exception handler.