The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

858 lines
35KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. //==============================================================================
  20. /** Used to build a tree of elements representing an XML document.
  21. An XML document can be parsed into a tree of XmlElements, each of which
  22. represents an XML tag structure, and which may itself contain other
  23. nested elements.
  24. An XmlElement can also be converted back into a text document, and has
  25. lots of useful methods for manipulating its attributes and sub-elements,
  26. so XmlElements can actually be used as a handy general-purpose data
  27. structure.
  28. Here's an example of parsing some elements: @code
  29. // check we're looking at the right kind of document..
  30. if (myElement->hasTagName ("ANIMALS"))
  31. {
  32. // now we'll iterate its sub-elements looking for 'giraffe' elements..
  33. for (auto* e : myElement->getChildIterator())
  34. {
  35. if (e->hasTagName ("GIRAFFE"))
  36. {
  37. // found a giraffe, so use some of its attributes..
  38. String giraffeName = e->getStringAttribute ("name");
  39. int giraffeAge = e->getIntAttribute ("age");
  40. bool isFriendly = e->getBoolAttribute ("friendly");
  41. }
  42. }
  43. }
  44. @endcode
  45. And here's an example of how to create an XML document from scratch: @code
  46. // create an outer node called "ANIMALS"
  47. XmlElement animalsList ("ANIMALS");
  48. for (int i = 0; i < numAnimals; ++i)
  49. {
  50. // create an inner element..
  51. XmlElement* giraffe = new XmlElement ("GIRAFFE");
  52. giraffe->setAttribute ("name", "nigel");
  53. giraffe->setAttribute ("age", 10);
  54. giraffe->setAttribute ("friendly", true);
  55. // ..and add our new element to the parent node
  56. animalsList.addChildElement (giraffe);
  57. }
  58. // now we can turn the whole thing into textual XML
  59. auto xmlString = animalsList.toString();
  60. @endcode
  61. @see parseXML, parseXMLIfTagMatches, XmlDocument
  62. @tags{Core}
  63. */
  64. class JUCE_API XmlElement
  65. {
  66. public:
  67. //==============================================================================
  68. /** Creates an XmlElement with this tag name. */
  69. explicit XmlElement (const String& tagName);
  70. /** Creates an XmlElement with this tag name. */
  71. explicit XmlElement (const char* tagName);
  72. /** Creates an XmlElement with this tag name. */
  73. explicit XmlElement (const Identifier& tagName);
  74. /** Creates an XmlElement with this tag name. */
  75. explicit XmlElement (StringRef tagName);
  76. /** Creates an XmlElement with this tag name. */
  77. XmlElement (String::CharPointerType tagNameBegin, String::CharPointerType tagNameEnd);
  78. /** Creates a (deep) copy of another element. */
  79. XmlElement (const XmlElement&);
  80. /** Creates a (deep) copy of another element. */
  81. XmlElement& operator= (const XmlElement&);
  82. /** Move assignment operator */
  83. XmlElement& operator= (XmlElement&&) noexcept;
  84. /** Move constructor */
  85. XmlElement (XmlElement&&) noexcept;
  86. /** Deleting an XmlElement will also delete all of its child elements. */
  87. ~XmlElement() noexcept;
  88. //==============================================================================
  89. /** Compares two XmlElements to see if they contain the same text and attributes.
  90. The elements are only considered equivalent if they contain the same attributes
  91. with the same values, and have the same sub-nodes.
  92. @param other the other element to compare to
  93. @param ignoreOrderOfAttributes if true, this means that two elements with the
  94. same attributes in a different order will be
  95. considered the same; if false, the attributes must
  96. be in the same order as well
  97. */
  98. bool isEquivalentTo (const XmlElement* other,
  99. bool ignoreOrderOfAttributes) const noexcept;
  100. //==============================================================================
  101. /** A struct containing options for formatting the text when representing an
  102. XML element as a string.
  103. */
  104. struct TextFormat
  105. {
  106. /** Default constructor. */
  107. TextFormat();
  108. String dtd; /**< If supplied, this DTD will be added to the document. */
  109. String customHeader; /**< If supplied, this header will be used (and customEncoding & addDefaultHeader will be ignored). */
  110. String customEncoding; /**< If not empty and addDefaultHeader is true, this will be set as the encoding. Otherwise, a default of "UTF-8" will be used */
  111. bool addDefaultHeader = true; /**< If true, a default header will be generated; otherwise just bare XML will be emitted. */
  112. int lineWrapLength = 60; /**< A maximum line length before wrapping is done. (If newLineChars is nullptr, this is ignored) */
  113. const char* newLineChars = "\r\n"; /**< Allows the newline characters to be set. If you set this to nullptr, then the whole XML document will be placed on a single line. */
  114. TextFormat singleLine() const; /**< returns a copy of this format with newLineChars set to nullptr. */
  115. TextFormat withoutHeader() const; /**< returns a copy of this format with the addDefaultHeader flag set to false. */
  116. };
  117. /** Returns a text version of this XML element.
  118. If your intention is to write the XML to a file or stream, it's probably more efficient to
  119. use writeTo() instead of creating an intermediate string.
  120. @see writeTo
  121. */
  122. String toString (const TextFormat& format = {}) const;
  123. /** Writes the document to a stream as UTF-8.
  124. @see writeTo, toString
  125. */
  126. void writeTo (OutputStream& output, const TextFormat& format = {}) const;
  127. /** Writes the document to a file as UTF-8.
  128. @see writeTo, toString
  129. */
  130. bool writeTo (const File& destinationFile, const TextFormat& format = {}) const;
  131. //==============================================================================
  132. /** Returns this element's tag type name.
  133. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would return "MOOSE".
  134. @see hasTagName
  135. */
  136. const String& getTagName() const noexcept { return tagName; }
  137. /** Returns the namespace portion of the tag-name, or an empty string if none is specified. */
  138. String getNamespace() const;
  139. /** Returns the part of the tag-name that follows any namespace declaration. */
  140. String getTagNameWithoutNamespace() const;
  141. /** Tests whether this element has a particular tag name.
  142. @param possibleTagName the tag name you're comparing it with
  143. @see getTagName
  144. */
  145. bool hasTagName (StringRef possibleTagName) const noexcept;
  146. /** Tests whether this element has a particular tag name, ignoring any XML namespace prefix.
  147. So a test for e.g. "xyz" will return true for "xyz" and also "foo:xyz", "bar::xyz", etc.
  148. @see getTagName
  149. */
  150. bool hasTagNameIgnoringNamespace (StringRef possibleTagName) const;
  151. /** Changes this elements tag name.
  152. @see getTagName
  153. */
  154. void setTagName (StringRef newTagName);
  155. //==============================================================================
  156. /** Returns the number of XML attributes this element contains.
  157. E.g. for an element such as \<MOOSE legs="4" antlers="2">, this would
  158. return 2.
  159. */
  160. int getNumAttributes() const noexcept;
  161. /** Returns the name of one of the elements attributes.
  162. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  163. getAttributeName(1) would return "antlers".
  164. @see getAttributeValue, getStringAttribute
  165. */
  166. const String& getAttributeName (int attributeIndex) const noexcept;
  167. /** Returns the value of one of the elements attributes.
  168. E.g. for an element such as \<MOOSE legs="4" antlers="2">, then
  169. getAttributeName(1) would return "2".
  170. @see getAttributeName, getStringAttribute
  171. */
  172. const String& getAttributeValue (int attributeIndex) const noexcept;
  173. //==============================================================================
  174. // Attribute-handling methods..
  175. /** Checks whether the element contains an attribute with a certain name. */
  176. bool hasAttribute (StringRef attributeName) const noexcept;
  177. /** Returns the value of a named attribute.
  178. @param attributeName the name of the attribute to look up
  179. */
  180. const String& getStringAttribute (StringRef attributeName) const noexcept;
  181. /** Returns the value of a named attribute.
  182. @param attributeName the name of the attribute to look up
  183. @param defaultReturnValue a value to return if the element doesn't have an attribute
  184. with this name
  185. */
  186. String getStringAttribute (StringRef attributeName, const String& defaultReturnValue) const;
  187. /** Compares the value of a named attribute with a value passed-in.
  188. @param attributeName the name of the attribute to look up
  189. @param stringToCompareAgainst the value to compare it with
  190. @param ignoreCase whether the comparison should be case-insensitive
  191. @returns true if the value of the attribute is the same as the string passed-in;
  192. false if it's different (or if no such attribute exists)
  193. */
  194. bool compareAttribute (StringRef attributeName,
  195. StringRef stringToCompareAgainst,
  196. bool ignoreCase = false) const noexcept;
  197. /** Returns the value of a named attribute as an integer.
  198. This will try to find the attribute and convert it to an integer (using
  199. the String::getIntValue() method).
  200. @param attributeName the name of the attribute to look up
  201. @param defaultReturnValue a value to return if the element doesn't have an attribute
  202. with this name
  203. @see setAttribute
  204. */
  205. int getIntAttribute (StringRef attributeName, int defaultReturnValue = 0) const;
  206. /** Returns the value of a named attribute as floating-point.
  207. This will try to find the attribute and convert it to a double (using
  208. the String::getDoubleValue() method).
  209. @param attributeName the name of the attribute to look up
  210. @param defaultReturnValue a value to return if the element doesn't have an attribute
  211. with this name
  212. @see setAttribute
  213. */
  214. double getDoubleAttribute (StringRef attributeName, double defaultReturnValue = 0.0) const;
  215. /** Returns the value of a named attribute as a boolean.
  216. This will try to find the attribute and interpret it as a boolean. To do this,
  217. it'll return true if the value is "1", "true", "y", etc, or false for other
  218. values.
  219. @param attributeName the name of the attribute to look up
  220. @param defaultReturnValue a value to return if the element doesn't have an attribute
  221. with this name
  222. */
  223. bool getBoolAttribute (StringRef attributeName, bool defaultReturnValue = false) const;
  224. /** Adds a named attribute to the element.
  225. If the element already contains an attribute with this name, it's value will
  226. be updated to the new value. If there's no such attribute yet, a new one will
  227. be added.
  228. Note that there are other setAttribute() methods that take integers,
  229. doubles, etc. to make it easy to store numbers.
  230. @param attributeName the name of the attribute to set
  231. @param newValue the value to set it to
  232. @see removeAttribute
  233. */
  234. void setAttribute (const Identifier& attributeName, const String& newValue);
  235. /** Adds a named attribute to the element, setting it to an integer value.
  236. If the element already contains an attribute with this name, it's value will
  237. be updated to the new value. If there's no such attribute yet, a new one will
  238. be added.
  239. Note that there are other setAttribute() methods that take integers,
  240. doubles, etc. to make it easy to store numbers.
  241. @param attributeName the name of the attribute to set
  242. @param newValue the value to set it to
  243. */
  244. void setAttribute (const Identifier& attributeName, int newValue);
  245. /** Adds a named attribute to the element, setting it to a floating-point value.
  246. If the element already contains an attribute with this name, it's value will
  247. be updated to the new value. If there's no such attribute yet, a new one will
  248. be added.
  249. Note that there are other setAttribute() methods that take integers,
  250. doubles, etc. to make it easy to store numbers.
  251. @param attributeName the name of the attribute to set
  252. @param newValue the value to set it to
  253. */
  254. void setAttribute (const Identifier& attributeName, double newValue);
  255. /** Removes a named attribute from the element.
  256. @param attributeName the name of the attribute to remove
  257. @see removeAllAttributes
  258. */
  259. void removeAttribute (const Identifier& attributeName) noexcept;
  260. /** Removes all attributes from this element. */
  261. void removeAllAttributes() noexcept;
  262. //==============================================================================
  263. // Child element methods..
  264. /** Returns the first of this element's sub-elements.
  265. see getNextElement() for an example of how to iterate the sub-elements.
  266. @see getChildIterator
  267. */
  268. XmlElement* getFirstChildElement() const noexcept { return firstChildElement; }
  269. /** Returns the next of this element's siblings.
  270. This can be used for iterating an element's sub-elements, e.g.
  271. @code
  272. XmlElement* child = myXmlDocument->getFirstChildElement();
  273. while (child != nullptr)
  274. {
  275. ...do stuff with this child..
  276. child = child->getNextElement();
  277. }
  278. @endcode
  279. Note that when iterating the child elements, some of them might be
  280. text elements as well as XML tags - use isTextElement() to work this
  281. out.
  282. Also, it's much easier and neater to use this method indirectly via the
  283. getChildIterator() method.
  284. @returns the sibling element that follows this one, or a nullptr if
  285. this is the last element in its parent
  286. @see getNextElement, isTextElement, getChildIterator
  287. */
  288. inline XmlElement* getNextElement() const noexcept { return nextListItem; }
  289. /** Returns the next of this element's siblings which has the specified tag
  290. name.
  291. This is like getNextElement(), but will scan through the list until it
  292. finds an element with the given tag name.
  293. @see getNextElement, getChildIterator
  294. */
  295. XmlElement* getNextElementWithTagName (StringRef requiredTagName) const;
  296. /** Returns the number of sub-elements in this element.
  297. @see getChildElement
  298. */
  299. int getNumChildElements() const noexcept;
  300. /** Returns the sub-element at a certain index.
  301. It's not very efficient to iterate the sub-elements by index - see
  302. getNextElement() for an example of how best to iterate.
  303. @returns the n'th child of this element, or nullptr if the index is out-of-range
  304. @see getNextElement, isTextElement, getChildByName
  305. */
  306. XmlElement* getChildElement (int index) const noexcept;
  307. /** Returns the first sub-element with a given tag-name.
  308. @param tagNameToLookFor the tag name of the element you want to find
  309. @returns the first element with this tag name, or nullptr if none is found
  310. @see getNextElement, isTextElement, getChildElement, getChildByAttribute
  311. */
  312. XmlElement* getChildByName (StringRef tagNameToLookFor) const noexcept;
  313. /** Returns the first sub-element which has an attribute that matches the given value.
  314. @param attributeName the name of the attribute to check
  315. @param attributeValue the target value of the attribute
  316. @returns the first element with this attribute value, or nullptr if none is found
  317. @see getChildByName
  318. */
  319. XmlElement* getChildByAttribute (StringRef attributeName,
  320. StringRef attributeValue) const noexcept;
  321. //==============================================================================
  322. /** Appends an element to this element's list of children.
  323. Child elements are deleted automatically when their parent is deleted, so
  324. make sure the object that you pass in will not be deleted by anything else,
  325. and make sure it's not already the child of another element.
  326. Note that due to the XmlElement using a singly-linked-list, prependChildElement()
  327. is an O(1) operation, but addChildElement() is an O(N) operation - so if
  328. you're adding large number of elements, you may prefer to do so in reverse order!
  329. @see getFirstChildElement, getNextElement, getNumChildElements,
  330. getChildElement, removeChildElement
  331. */
  332. void addChildElement (XmlElement* newChildElement) noexcept;
  333. /** Inserts an element into this element's list of children.
  334. Child elements are deleted automatically when their parent is deleted, so
  335. make sure the object that you pass in will not be deleted by anything else,
  336. and make sure it's not already the child of another element.
  337. @param newChildElement the element to add
  338. @param indexToInsertAt the index at which to insert the new element - if this is
  339. below zero, it will be added to the end of the list
  340. @see addChildElement, insertChildElement
  341. */
  342. void insertChildElement (XmlElement* newChildElement,
  343. int indexToInsertAt) noexcept;
  344. /** Inserts an element at the beginning of this element's list of children.
  345. Child elements are deleted automatically when their parent is deleted, so
  346. make sure the object that you pass in will not be deleted by anything else,
  347. and make sure it's not already the child of another element.
  348. Note that due to the XmlElement using a singly-linked-list, prependChildElement()
  349. is an O(1) operation, but addChildElement() is an O(N) operation - so if
  350. you're adding large number of elements, you may prefer to do so in reverse order!
  351. @see addChildElement, insertChildElement
  352. */
  353. void prependChildElement (XmlElement* newChildElement) noexcept;
  354. /** Creates a new element with the given name and returns it, after adding it
  355. as a child element.
  356. This is a handy method that means that instead of writing this:
  357. @code
  358. XmlElement* newElement = new XmlElement ("foobar");
  359. myParentElement->addChildElement (newElement);
  360. @endcode
  361. ..you could just write this:
  362. @code
  363. XmlElement* newElement = myParentElement->createNewChildElement ("foobar");
  364. @endcode
  365. */
  366. XmlElement* createNewChildElement (StringRef tagName);
  367. /** Replaces one of this element's children with another node.
  368. If the current element passed-in isn't actually a child of this element,
  369. this will return false and the new one won't be added. Otherwise, the
  370. existing element will be deleted, replaced with the new one, and it
  371. will return true.
  372. */
  373. bool replaceChildElement (XmlElement* currentChildElement,
  374. XmlElement* newChildNode) noexcept;
  375. /** Removes a child element.
  376. @param childToRemove the child to look for and remove
  377. @param shouldDeleteTheChild if true, the child will be deleted, if false it'll
  378. just remove it
  379. */
  380. void removeChildElement (XmlElement* childToRemove,
  381. bool shouldDeleteTheChild) noexcept;
  382. /** Deletes all the child elements in the element.
  383. @see removeChildElement, deleteAllChildElementsWithTagName
  384. */
  385. void deleteAllChildElements() noexcept;
  386. /** Deletes all the child elements with a given tag name.
  387. @see removeChildElement
  388. */
  389. void deleteAllChildElementsWithTagName (StringRef tagName) noexcept;
  390. /** Returns true if the given element is a child of this one. */
  391. bool containsChildElement (const XmlElement* possibleChild) const noexcept;
  392. /** Recursively searches all sub-elements of this one, looking for an element
  393. which is the direct parent of the specified element.
  394. Because elements don't store a pointer to their parent, if you have one
  395. and need to find its parent, the only way to do so is to exhaustively
  396. search the whole tree for it.
  397. If the given child is found somewhere in this element's hierarchy, then
  398. this method will return its parent. If not, it will return nullptr.
  399. */
  400. XmlElement* findParentElementOf (const XmlElement* childToSearchFor) noexcept;
  401. //==============================================================================
  402. /** Sorts the child elements using a comparator.
  403. This will use a comparator object to sort the elements into order. The object
  404. passed must have a method of the form:
  405. @code
  406. int compareElements (const XmlElement* first, const XmlElement* second);
  407. @endcode
  408. ..and this method must return:
  409. - a value of < 0 if the first comes before the second
  410. - a value of 0 if the two objects are equivalent
  411. - a value of > 0 if the second comes before the first
  412. To improve performance, the compareElements() method can be declared as static or const.
  413. @param comparator the comparator to use for comparing elements.
  414. @param retainOrderOfEquivalentItems if this is true, then items which the comparator
  415. says are equivalent will be kept in the order in which they
  416. currently appear in the array. This is slower to perform, but
  417. may be important in some cases. If it's false, a faster algorithm
  418. is used, but equivalent elements may be rearranged.
  419. */
  420. template <class ElementComparator>
  421. void sortChildElements (ElementComparator& comparator,
  422. bool retainOrderOfEquivalentItems = false)
  423. {
  424. auto num = getNumChildElements();
  425. if (num > 1)
  426. {
  427. HeapBlock<XmlElement*> elems (num);
  428. getChildElementsAsArray (elems);
  429. sortArray (comparator, (XmlElement**) elems, 0, num - 1, retainOrderOfEquivalentItems);
  430. reorderChildElements (elems, num);
  431. }
  432. }
  433. //==============================================================================
  434. /** Returns true if this element is a section of text.
  435. Elements can either be an XML tag element or a section of text, so this
  436. is used to find out what kind of element this one is.
  437. @see getAllText, addTextElement, deleteAllTextElements
  438. */
  439. bool isTextElement() const noexcept;
  440. /** Returns the text for a text element.
  441. Note that if you have an element like this:
  442. @code<xyz>hello</xyz>@endcode
  443. then calling getText on the "xyz" element won't return "hello", because that is
  444. actually stored in a special text sub-element inside the xyz element. To get the
  445. "hello" string, you could either call getText on the (unnamed) sub-element, or
  446. use getAllSubText() to do this automatically.
  447. Note that leading and trailing whitespace will be included in the string - to remove
  448. if, just call String::trim() on the result.
  449. @see isTextElement, getAllSubText, getChildElementAllSubText
  450. */
  451. const String& getText() const noexcept;
  452. /** Sets the text in a text element.
  453. Note that this is only a valid call if this element is a text element. If it's
  454. not, then no action will be performed. If you're trying to add text inside a normal
  455. element, you probably want to use addTextElement() instead.
  456. */
  457. void setText (const String& newText);
  458. /** Returns all the text from this element's child nodes.
  459. This iterates all the child elements and when it finds text elements,
  460. it concatenates their text into a big string which it returns.
  461. E.g. @code<xyz>hello <x>there</x> world</xyz>@endcode
  462. if you called getAllSubText on the "xyz" element, it'd return "hello there world".
  463. Note that leading and trailing whitespace will be included in the string - to remove
  464. if, just call String::trim() on the result.
  465. @see isTextElement, getChildElementAllSubText, getText, addTextElement
  466. */
  467. String getAllSubText() const;
  468. /** Returns all the sub-text of a named child element.
  469. If there is a child element with the given tag name, this will return
  470. all of its sub-text (by calling getAllSubText() on it). If there is
  471. no such child element, this will return the default string passed-in.
  472. @see getAllSubText
  473. */
  474. String getChildElementAllSubText (StringRef childTagName,
  475. const String& defaultReturnValue) const;
  476. /** Appends a section of text to this element.
  477. @see isTextElement, getText, getAllSubText
  478. */
  479. void addTextElement (const String& text);
  480. /** Removes all the text elements from this element.
  481. @see isTextElement, getText, getAllSubText, addTextElement
  482. */
  483. void deleteAllTextElements() noexcept;
  484. /** Creates a text element that can be added to a parent element. */
  485. static XmlElement* createTextElement (const String& text);
  486. /** Checks if a given string is a valid XML name */
  487. static bool isValidXmlName (StringRef possibleName) noexcept;
  488. private:
  489. //==============================================================================
  490. struct GetNextElement
  491. {
  492. XmlElement* getNext (const XmlElement& e) const { return e.getNextElement(); }
  493. };
  494. struct GetNextElementWithTagName
  495. {
  496. GetNextElementWithTagName() = default;
  497. explicit GetNextElementWithTagName (String n) : name (std::move (n)) {}
  498. XmlElement* getNext (const XmlElement& e) const { return e.getNextElementWithTagName (name); }
  499. String name;
  500. };
  501. //==============================================================================
  502. template <typename Traits>
  503. class Iterator : private Traits
  504. {
  505. public:
  506. using difference_type = ptrdiff_t;
  507. using value_type = XmlElement*;
  508. using pointer = const value_type*;
  509. using reference = value_type;
  510. using iterator_category = std::input_iterator_tag;
  511. Iterator() = default;
  512. template <typename... Args>
  513. Iterator (XmlElement* e, Args&&... args)
  514. : Traits (std::forward<Args> (args)...), element (e) {}
  515. Iterator begin() const { return *this; }
  516. Iterator end() const { return Iterator{}; }
  517. bool operator== (const Iterator& other) const { return element == other.element; }
  518. bool operator!= (const Iterator& other) const { return ! operator== (other); }
  519. reference operator*() const { return element; }
  520. pointer operator->() const { return &element; }
  521. Iterator& operator++()
  522. {
  523. element = Traits::getNext (*element);
  524. return *this;
  525. }
  526. Iterator operator++(int)
  527. {
  528. auto copy = *this;
  529. ++(*this);
  530. return copy;
  531. }
  532. private:
  533. value_type element = nullptr;
  534. };
  535. public:
  536. //==============================================================================
  537. /** Allows iterating the children of an XmlElement using range-for syntax.
  538. @code
  539. void doSomethingWithXmlChildren (const XmlElement& myParentXml)
  540. {
  541. for (auto* element : myParentXml.getChildIterator())
  542. doSomethingWithXmlElement (element);
  543. }
  544. @endcode
  545. */
  546. Iterator<GetNextElement> getChildIterator() const
  547. {
  548. return Iterator<GetNextElement> { getFirstChildElement() };
  549. }
  550. /** Allows iterating children of an XmlElement with a specific tag using range-for syntax.
  551. @code
  552. void doSomethingWithXmlChildren (const XmlElement& myParentXml)
  553. {
  554. for (auto* element : myParentXml.getChildWithTagNameIterator ("MYTAG"))
  555. doSomethingWithXmlElement (element);
  556. }
  557. @endcode
  558. */
  559. Iterator<GetNextElementWithTagName> getChildWithTagNameIterator (StringRef name) const
  560. {
  561. return Iterator<GetNextElementWithTagName> { getChildByName (name), name };
  562. }
  563. #ifndef DOXYGEN
  564. [[deprecated]] void macroBasedForLoop() const noexcept {}
  565. [[deprecated ("This has been deprecated in favour of the toString method.")]]
  566. String createDocument (StringRef dtdToUse,
  567. bool allOnOneLine = false,
  568. bool includeXmlHeader = true,
  569. StringRef encodingType = "UTF-8",
  570. int lineWrapLength = 60) const;
  571. [[deprecated ("This has been deprecated in favour of the writeTo method.")]]
  572. void writeToStream (OutputStream& output,
  573. StringRef dtdToUse,
  574. bool allOnOneLine = false,
  575. bool includeXmlHeader = true,
  576. StringRef encodingType = "UTF-8",
  577. int lineWrapLength = 60) const;
  578. [[deprecated ("This has been deprecated in favour of the writeTo method.")]]
  579. bool writeToFile (const File& destinationFile,
  580. StringRef dtdToUse,
  581. StringRef encodingType = "UTF-8",
  582. int lineWrapLength = 60) const;
  583. #endif
  584. private:
  585. //==============================================================================
  586. struct XmlAttributeNode
  587. {
  588. XmlAttributeNode (const XmlAttributeNode&) noexcept;
  589. XmlAttributeNode (const Identifier&, const String&) noexcept;
  590. XmlAttributeNode (String::CharPointerType, String::CharPointerType);
  591. LinkedListPointer<XmlAttributeNode> nextListItem;
  592. Identifier name;
  593. String value;
  594. private:
  595. XmlAttributeNode& operator= (const XmlAttributeNode&) = delete;
  596. };
  597. friend class XmlDocument;
  598. friend class LinkedListPointer<XmlAttributeNode>;
  599. friend class LinkedListPointer<XmlElement>;
  600. friend class LinkedListPointer<XmlElement>::Appender;
  601. friend class NamedValueSet;
  602. LinkedListPointer<XmlElement> nextListItem, firstChildElement;
  603. LinkedListPointer<XmlAttributeNode> attributes;
  604. String tagName;
  605. XmlElement (int) noexcept;
  606. void copyChildrenAndAttributesFrom (const XmlElement&);
  607. void writeElementAsText (OutputStream&, int, int, const char*) const;
  608. void getChildElementsAsArray (XmlElement**) const noexcept;
  609. void reorderChildElements (XmlElement**, int) noexcept;
  610. XmlAttributeNode* getAttribute (StringRef) const noexcept;
  611. // Sigh.. L"" or _T("") string literals are problematic in general, and really inappropriate
  612. // for XML tags. Use a UTF-8 encoded literal instead, or if you're really determined to use
  613. // UTF-16, cast it to a String and use the other constructor.
  614. XmlElement (const wchar_t*) = delete;
  615. JUCE_LEAK_DETECTOR (XmlElement)
  616. };
  617. //==============================================================================
  618. #ifndef DOXYGEN
  619. /** DEPRECATED: A handy macro to make it easy to iterate all the child elements in an XmlElement.
  620. New code should avoid this macro, and instead use getChildIterator directly.
  621. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  622. will be the name of a pointer to each child element.
  623. E.g. @code
  624. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  625. forEachXmlChildElement (*myParentXml, child)
  626. {
  627. if (child->hasTagName ("FOO"))
  628. doSomethingWithXmlElement (child);
  629. }
  630. @endcode
  631. @see forEachXmlChildElementWithTagName
  632. */
  633. #define forEachXmlChildElement(parentXmlElement, childElementVariableName) \
  634. for (auto* (childElementVariableName) : ((parentXmlElement).macroBasedForLoop(), (parentXmlElement).getChildIterator()))
  635. /** DEPRECATED: A macro that makes it easy to iterate all the child elements of an XmlElement
  636. which have a specified tag.
  637. New code should avoid this macro, and instead use getChildWithTagNameIterator directly.
  638. This does the same job as the forEachXmlChildElement macro, but only for those
  639. elements that have a particular tag name.
  640. The parentXmlElement should be a reference to the parent XML, and the childElementVariableName
  641. will be the name of a pointer to each child element. The requiredTagName is the
  642. tag name to match.
  643. E.g. @code
  644. XmlElement* myParentXml = createSomeKindOfXmlDocument();
  645. forEachXmlChildElementWithTagName (*myParentXml, child, "MYTAG")
  646. {
  647. // the child object is now guaranteed to be a <MYTAG> element..
  648. doSomethingWithMYTAGElement (child);
  649. }
  650. @endcode
  651. @see forEachXmlChildElement
  652. */
  653. #define forEachXmlChildElementWithTagName(parentXmlElement, childElementVariableName, requiredTagName) \
  654. for (auto* (childElementVariableName) : ((parentXmlElement).macroBasedForLoop(), (parentXmlElement).getChildWithTagNameIterator ((requiredTagName))))
  655. #endif
  656. } // namespace juce