XML
Data / CompositeDescription
Represents an XML element. Load with loadXML() or parseXML(). Access children and attributes by name.
Syntax
XML xml = loadXML("data.xml")
XML* child = xml.getChild("element")
Parameters
None
Returns
XMLMethods
| getName() | Returns the name of the element |
| getContent() | Returns the text content of the element |
| getAttribute(std::string k) | Returns the value of an attribute |
| getAttributeInt(std::string k) | Returns an attribute as int |
| getAttributeFloat(std::string k) | Returns an attribute as float |
| setAttribute(std::string k, std::string v) | Sets an attribute value |
| setContent(std::string c) | Sets the text content |
| addChild(std::string name) | Adds a child element |
| getChild(int i) | Gets child by index |
| getChild(std::string name) | Gets child by tag name |
| getChildCount() | Returns number of children |
| getChildren(std::string name) | Returns all children with given tag name |
Related
Under the Hood
From Processing.h:
struct XML {
std::string name, content;
std::map<std::string,std::string> attributes;
std::vector<XML> children;
XML() = default;
explicit XML(const std::string& n) : name(n) {}
std::string getName() const { return name; }
std::string getContent() const { return content; }
bool hasAttribute(const std::string& k) const { return attributes.count(k)>0; }
std::string getAttribute(const std::string& k, const std::string& def="") const {
auto it = attributes.find(k);
return it != attributes.end() ? it->second : def;
}
int getAttributeInt(const std::string& k, int def=0) const { return hasAttribute(k) ? std::stoi(attributes.at(k)) : def; }
float getAttributeFloat(const std::string& k, float def=0) const { return hasAttribute(k) ? std::stof(attributes.at(k)) : def; }
void setAttribute(const std::string& k, const std::string& v) { attributes[k]=v; }
void setContent(const std::string& c) { content=c; }
XML* addChild(const std::string& n) { children.push_back(XML(n)); return &children.back(); }
XML* getChild(int i) { return i<(int)children.size()?&children[i]:nullptr; }
XML* getChild(const std::string& n) { for(auto& c:children) if(c.name==n) return &c; return nullptr; }
int getChildCount() const { return (int)children.size(); }
std::vector<XML*> getChildren(const std::string& n){ std::vector<XML*> r; for(auto& c:children) if(c.name==n) r.push_back(&c); return r; }
std::string toString(int indent=0) const;
};