VirtualBox

source: vbox/trunk/include/iprt/cpp/xml.h@ 95897

Last change on this file since 95897 was 95109, checked in by vboxsync, 3 years ago

IPRT/xml: Having another go at the PFNEXTERNALENTITYLOADER declaration to make it work for VC++ in c++17 mode. (noexcept/c++17)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 42.4 KB
Line 
1/** @file
2 * IPRT - XML Helper APIs.
3 */
4
5/*
6 * Copyright (C) 2007-2022 Oracle Corporation
7 *
8 * This file is part of VirtualBox Open Source Edition (OSE), as
9 * available from http://www.virtualbox.org. This file is free software;
10 * you can redistribute it and/or modify it under the terms of the GNU
11 * General Public License (GPL) as published by the Free Software
12 * Foundation, in version 2 as it comes in the "COPYING" file of the
13 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
14 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
15 *
16 * The contents of this file may alternatively be used under the terms
17 * of the Common Development and Distribution License Version 1.0
18 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
19 * VirtualBox OSE distribution, in which case the provisions of the
20 * CDDL are applicable instead of those of the GPL.
21 *
22 * You may elect to license modified versions of this file under the
23 * terms and conditions of either the GPL or the CDDL or both.
24 */
25
26#ifndef IPRT_INCLUDED_cpp_xml_h
27#define IPRT_INCLUDED_cpp_xml_h
28#ifndef RT_WITHOUT_PRAGMA_ONCE
29# pragma once
30#endif
31
32#ifndef IN_RING3
33# error "There are no XML APIs available in Ring-0 Context!"
34#endif
35
36#include <iprt/list.h>
37#include <iprt/cpp/exception.h>
38#include <iprt/cpp/utils.h>
39
40#include <list>
41#include <memory>
42
43
44/** @defgroup grp_rt_cpp_xml C++ XML support
45 * @ingroup grp_rt_cpp
46 * @{
47 */
48
49/* Forwards */
50typedef struct _xmlParserInput xmlParserInput;
51typedef xmlParserInput *xmlParserInputPtr;
52typedef struct _xmlParserCtxt xmlParserCtxt;
53typedef xmlParserCtxt *xmlParserCtxtPtr;
54typedef struct _xmlError xmlError;
55typedef xmlError *xmlErrorPtr;
56
57typedef struct _xmlAttr xmlAttr;
58typedef struct _xmlNode xmlNode;
59
60#define RT_XML_CONTENT_SMALL _8K
61#define RT_XML_CONTENT_LARGE _128K
62#define RT_XML_ATTR_TINY 64
63#define RT_XML_ATTR_SMALL _1K
64#define RT_XML_ATTR_MEDIUM _8K
65#define RT_XML_ATTR_LARGE _64K
66
67/** @} */
68
69namespace xml
70{
71
72/**
73 * @addtogroup grp_rt_cpp_xml
74 * @{
75 */
76
77// Exceptions
78//////////////////////////////////////////////////////////////////////////////
79
80class RT_DECL_CLASS LogicError : public RTCError
81{
82public:
83
84 LogicError(const char *aMsg = NULL)
85 : RTCError(aMsg)
86 {}
87
88 LogicError(RT_SRC_POS_DECL);
89};
90
91class RT_DECL_CLASS RuntimeError : public RTCError
92{
93public:
94
95 RuntimeError(const char *aMsg = NULL)
96 : RTCError(aMsg)
97 {}
98};
99
100class RT_DECL_CLASS XmlError : public RuntimeError
101{
102public:
103 XmlError(xmlErrorPtr aErr);
104
105 static char* Format(xmlErrorPtr aErr);
106};
107
108// Logical errors
109//////////////////////////////////////////////////////////////////////////////
110
111class RT_DECL_CLASS ENotImplemented : public LogicError
112{
113public:
114 ENotImplemented(const char *aMsg = NULL) : LogicError(aMsg) {}
115 ENotImplemented(RT_SRC_POS_DECL) : LogicError(RT_SRC_POS_ARGS) {}
116};
117
118class RT_DECL_CLASS EInvalidArg : public LogicError
119{
120public:
121 EInvalidArg(const char *aMsg = NULL) : LogicError(aMsg) {}
122 EInvalidArg(RT_SRC_POS_DECL) : LogicError(RT_SRC_POS_ARGS) {}
123};
124
125class RT_DECL_CLASS EDocumentNotEmpty : public LogicError
126{
127public:
128 EDocumentNotEmpty(const char *aMsg = NULL) : LogicError(aMsg) {}
129 EDocumentNotEmpty(RT_SRC_POS_DECL) : LogicError(RT_SRC_POS_ARGS) {}
130};
131
132class RT_DECL_CLASS ENodeIsNotElement : public LogicError
133{
134public:
135 ENodeIsNotElement(const char *aMsg = NULL) : LogicError(aMsg) {}
136 ENodeIsNotElement(RT_SRC_POS_DECL) : LogicError(RT_SRC_POS_ARGS) {}
137};
138
139// Runtime errors
140//////////////////////////////////////////////////////////////////////////////
141
142class RT_DECL_CLASS EIPRTFailure : public RuntimeError
143{
144public:
145
146 EIPRTFailure(int aRC, const char *pszContextFmt, ...);
147
148 int rc() const
149 {
150 return mRC;
151 }
152
153private:
154 int mRC;
155};
156
157/**
158 * The Stream class is a base class for I/O streams.
159 */
160class RT_DECL_CLASS Stream
161{
162public:
163
164 virtual ~Stream() {}
165
166 virtual const char *uri() const = 0;
167
168 /**
169 * Returns the current read/write position in the stream. The returned
170 * position is a zero-based byte offset from the beginning of the file.
171 *
172 * Throws ENotImplemented if this operation is not implemented for the
173 * given stream.
174 */
175 virtual uint64_t pos() const = 0;
176
177 /**
178 * Sets the current read/write position in the stream.
179 *
180 * @param aPos Zero-based byte offset from the beginning of the stream.
181 *
182 * Throws ENotImplemented if this operation is not implemented for the
183 * given stream.
184 */
185 virtual void setPos (uint64_t aPos) = 0;
186};
187
188/**
189 * The Input class represents an input stream.
190 *
191 * This input stream is used to read the settings tree from.
192 * This is an abstract class that must be subclassed in order to fill it with
193 * useful functionality.
194 */
195class RT_DECL_CLASS Input : virtual public Stream
196{
197public:
198
199 /**
200 * Reads from the stream to the supplied buffer.
201 *
202 * @param aBuf Buffer to store read data to.
203 * @param aLen Buffer length.
204 *
205 * @return Number of bytes read.
206 */
207 virtual int read (char *aBuf, int aLen) = 0;
208};
209
210/**
211 *
212 */
213class RT_DECL_CLASS Output : virtual public Stream
214{
215public:
216
217 /**
218 * Writes to the stream from the supplied buffer.
219 *
220 * @param aBuf Buffer to write data from.
221 * @param aLen Buffer length.
222 *
223 * @return Number of bytes written.
224 */
225 virtual int write (const char *aBuf, int aLen) = 0;
226
227 /**
228 * Truncates the stream from the current position and upto the end.
229 * The new file size will become exactly #pos() bytes.
230 *
231 * Throws ENotImplemented if this operation is not implemented for the
232 * given stream.
233 */
234 virtual void truncate() = 0;
235};
236
237
238//////////////////////////////////////////////////////////////////////////////
239
240/**
241 * The File class is a stream implementation that reads from and writes to
242 * regular files.
243 *
244 * The File class uses IPRT File API for file operations. Note that IPRT File
245 * API is not thread-safe. This means that if you pass the same RTFILE handle to
246 * different File instances that may be simultaneously used on different
247 * threads, you should care about serialization; otherwise you will get garbage
248 * when reading from or writing to such File instances.
249 */
250class RT_DECL_CLASS File : public Input, public Output
251{
252public:
253
254 /**
255 * Possible file access modes.
256 */
257 enum Mode { Mode_Read, Mode_WriteCreate, Mode_Overwrite, Mode_ReadWrite };
258
259 /**
260 * Opens a file with the given name in the given mode. If @a aMode is Read
261 * or ReadWrite, the file must exist. If @a aMode is Write, the file must
262 * not exist. Otherwise, an EIPRTFailure exception will be thrown.
263 *
264 * @param aMode File mode.
265 * @param aFileName File name.
266 * @param aFlushIt Whether to flush a writable file before closing it.
267 */
268 File(Mode aMode, const char *aFileName, bool aFlushIt = false);
269
270 /**
271 * Uses the given file handle to perform file operations. This file
272 * handle must be already open in necessary mode (read, or write, or mixed).
273 *
274 * The read/write position of the given handle will be reset to the
275 * beginning of the file on success.
276 *
277 * Note that the given file handle will not be automatically closed upon
278 * this object destruction.
279 *
280 * @note It you pass the same RTFILE handle to more than one File instance,
281 * please make sure you have provided serialization in case if these
282 * instasnces are to be simultaneously used by different threads.
283 * Otherwise you may get garbage when reading or writing.
284 *
285 * @param aHandle Open file handle.
286 * @param aFileName File name (for reference).
287 * @param aFlushIt Whether to flush a writable file before closing it.
288 */
289 File(RTFILE aHandle, const char *aFileName = NULL, bool aFlushIt = false);
290
291 /**
292 * Destroys the File object. If the object was created from a file name
293 * the corresponding file will be automatically closed. If the object was
294 * created from a file handle, it will remain open.
295 */
296 virtual ~File();
297
298 const char *uri() const;
299
300 uint64_t pos() const;
301 void setPos(uint64_t aPos);
302
303 /**
304 * See Input::read(). If this method is called in wrong file mode,
305 * LogicError will be thrown.
306 */
307 int read(char *aBuf, int aLen);
308
309 /**
310 * See Output::write(). If this method is called in wrong file mode,
311 * LogicError will be thrown.
312 */
313 int write(const char *aBuf, int aLen);
314
315 /**
316 * See Output::truncate(). If this method is called in wrong file mode,
317 * LogicError will be thrown.
318 */
319 void truncate();
320
321private:
322
323 /* Obscure class data */
324 struct Data;
325 Data *m;
326
327 /* auto_ptr data doesn't have proper copy semantics */
328 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP(File);
329};
330
331/**
332 * The MemoryBuf class represents a stream implementation that reads from the
333 * memory buffer.
334 */
335class RT_DECL_CLASS MemoryBuf : public Input
336{
337public:
338
339 MemoryBuf (const char *aBuf, size_t aLen, const char *aURI = NULL);
340
341 virtual ~MemoryBuf();
342
343 const char *uri() const;
344
345 int read(char *aBuf, int aLen);
346 uint64_t pos() const;
347 void setPos(uint64_t aPos);
348
349private:
350 /* Obscure class data */
351 struct Data;
352 Data *m;
353
354 /* auto_ptr data doesn't have proper copy semantics */
355 DECLARE_CLS_COPY_CTOR_ASSIGN_NOOP(MemoryBuf);
356};
357
358
359/*
360 * GlobalLock
361 *
362 *
363 */
364
365
366typedef DECLCALLBACKTYPE_EX(xmlParserInput *, RT_NOTHING, FNEXTERNALENTITYLOADER,(const char *aURI, const char *aID,
367 xmlParserCtxt *aCtxt));
368typedef FNEXTERNALENTITYLOADER *PFNEXTERNALENTITYLOADER; /**< xmlExternalEntityLoader w/ noexcept. */
369
370class RT_DECL_CLASS GlobalLock
371{
372public:
373 GlobalLock();
374 ~GlobalLock();
375
376 void setExternalEntityLoader(PFNEXTERNALENTITYLOADER pFunc);
377
378 static xmlParserInput* callDefaultLoader(const char *aURI,
379 const char *aID,
380 xmlParserCtxt *aCtxt);
381
382private:
383 /* Obscure class data. */
384 struct Data;
385 struct Data *m;
386};
387
388class ElementNode;
389typedef std::list<const ElementNode*> ElementNodesList;
390
391class AttributeNode;
392
393class ContentNode;
394
395/**
396 * Node base class.
397 *
398 * Cannot be used directly, but ElementNode, ContentNode and AttributeNode
399 * derive from this. This does implement useful public methods though.
400 *
401 *
402 */
403class RT_DECL_CLASS Node
404{
405public:
406 virtual ~Node();
407
408 const char *getName() const;
409 const char *getPrefix() const;
410 const char *getNamespaceURI() const;
411 bool nameEqualsNS(const char *pcszNamespace, const char *pcsz) const;
412 bool nameEquals(const char *pcsz) const
413 {
414 return nameEqualsNS(NULL, pcsz);
415 }
416 bool nameEqualsN(const char *pcsz, size_t cchMax, const char *pcszNamespace = NULL) const;
417
418 const char *getValue() const;
419 const char *getValueN(size_t cchValueLimit) const;
420 bool copyValue(int32_t &i) const;
421 bool copyValue(uint32_t &i) const;
422 bool copyValue(int64_t &i) const;
423 bool copyValue(uint64_t &i) const;
424
425 /** @name Introspection.
426 * @{ */
427 /** Is this an ElementNode instance.
428 * @returns true / false */
429 bool isElement() const
430 {
431 return m_Type == IsElement;
432 }
433
434 /** Is this an ContentNode instance.
435 * @returns true / false */
436 bool isContent() const
437 {
438 return m_Type == IsContent;
439 }
440
441 /** Is this an AttributeNode instance.
442 * @returns true / false */
443 bool isAttribute() const
444 {
445 return m_Type == IsAttribute;
446 }
447
448 int getLineNumber() const;
449 /** @} */
450
451 /** @name General tree enumeration.
452 *
453 * Use the introspection methods isElement() and isContent() before doing static
454 * casting. Parents are always or ElementNode type, but siblings and children
455 * can be of both ContentNode and ElementNode types.
456 *
457 * @remarks Attribute node are in the attributes list, while both content and
458 * element nodes are in the list of children. See ElementNode.
459 *
460 * @remarks Careful mixing tree walking with node removal!
461 * @{
462 */
463 /** Get the parent node
464 * @returns Pointer to the parent node, or NULL if root. */
465 const Node *getParent() const
466 {
467 return m_pParent;
468 }
469
470 /** Get the previous sibling.
471 * @returns Pointer to the previous sibling node, NULL if first child.
472 */
473 const Node *getPrevSibiling() const
474 {
475 if (!m_pParentListAnchor)
476 return NULL;
477 return RTListGetPrevCpp(m_pParentListAnchor, this, const Node, m_listEntry);
478 }
479
480 /** Get the next sibling.
481 * @returns Pointer to the next sibling node, NULL if last child. */
482 const Node *getNextSibiling() const
483 {
484 if (!m_pParentListAnchor)
485 return NULL;
486 return RTListGetNextCpp(m_pParentListAnchor, this, const Node, m_listEntry);
487 }
488 /** @} */
489
490protected:
491 /** Node types. */
492 typedef enum { IsElement, IsAttribute, IsContent } EnumType;
493
494 /** The type of node this is an instance of. */
495 EnumType m_Type;
496 /** The parent node (always an element), NULL if root. */
497 Node *m_pParent;
498
499 xmlNode *m_pLibNode; ///< != NULL if this is an element or content node
500 xmlAttr *m_pLibAttr; ///< != NULL if this is an attribute node
501 const char *m_pcszNamespacePrefix; ///< not always set
502 const char *m_pcszNamespaceHref; ///< full http:// spec
503 const char *m_pcszName; ///< element or attribute name, points either into pLibNode or pLibAttr;
504 ///< NULL if this is a content node
505
506 /** Child list entry of this node. (List head m_pParent->m_children or
507 * m_pParent->m_attribute depending on the type.) */
508 RTLISTNODE m_listEntry;
509 /** Pointer to the parent list anchor.
510 * This allows us to use m_listEntry both for children and attributes. */
511 PRTLISTANCHOR m_pParentListAnchor;
512
513 // hide the default constructor so people use only our factory methods
514 Node(EnumType type,
515 Node *pParent,
516 PRTLISTANCHOR pListAnchor,
517 xmlNode *pLibNode,
518 xmlAttr *pLibAttr);
519 Node(const Node &x); // no copying
520
521 friend class AttributeNode;
522 friend class ElementNode; /* C list hack. */
523};
524
525/**
526 * Node subclass that represents an attribute of an element.
527 *
528 * For attributes, Node::getName() returns the attribute name, and Node::getValue()
529 * returns the attribute value, if any.
530 *
531 * Since the Node constructor is private, one can create new attribute nodes
532 * only through the following factory methods:
533 *
534 * -- ElementNode::setAttribute()
535 */
536class RT_DECL_CLASS AttributeNode : public Node
537{
538public:
539
540protected:
541 // hide the default constructor so people use only our factory methods
542 AttributeNode(const ElementNode *pElmRoot,
543 Node *pParent,
544 PRTLISTANCHOR pListAnchor,
545 xmlAttr *pLibAttr);
546 AttributeNode(const AttributeNode &x); // no copying
547
548 friend class Node;
549 friend class ElementNode;
550};
551
552/**
553 * Node subclass that represents an element.
554 *
555 * For elements, Node::getName() returns the element name, and Node::getValue()
556 * returns the text contents, if any.
557 *
558 * Since the Node constructor is private, one can create element nodes
559 * only through the following factory methods:
560 *
561 * -- Document::createRootElement()
562 * -- ElementNode::createChild()
563 */
564class RT_DECL_CLASS ElementNode : public Node
565{
566public:
567 int getChildElements(ElementNodesList &children, const char *pcszMatch = NULL) const;
568
569 const ElementNode *findChildElementNS(const char *pcszNamespace, const char *pcszMatch) const;
570 const ElementNode *findChildElement(const char *pcszMatch) const
571 {
572 return findChildElementNS(NULL, pcszMatch);
573 }
574 const ElementNode *findChildElementFromId(const char *pcszId) const;
575
576 /** Finds the first decendant matching the name at the end of @a pcszPath and
577 * optionally namespace.
578 *
579 * @returns Pointer to the child string value, NULL if not found or no value.
580 * @param pcszPath Path to the child element. Slashes can be used to
581 * make a simple path to any decendant.
582 * @param pcszNamespace The namespace to match, NULL (default) match any
583 * namespace. When using a path, this matches all
584 * elements along the way.
585 * @see findChildElement, findChildElementP
586 */
587 const ElementNode *findChildElementP(const char *pcszPath, const char *pcszNamespace = NULL) const;
588
589 /** Finds the first child with matching the give name and optionally namspace,
590 * returning its value.
591 *
592 * @returns Pointer to the child string value, NULL if not found or no value.
593 * @param pcszPath Path to the child element. Slashes can be used to
594 * make a simple path to any decendant.
595 * @param pcszNamespace The namespace to match, NULL (default) match any
596 * namespace. When using a path, this matches all
597 * elements along the way.
598 * @see findChildElement, findChildElementP
599 */
600 const char *findChildElementValueP(const char *pcszPath, const char *pcszNamespace = NULL) const
601 {
602 const ElementNode *pElem = findChildElementP(pcszPath, pcszNamespace);
603 if (pElem)
604 return pElem->getValue();
605 return NULL;
606 }
607
608 /** Finds the first child with matching the give name and optionally namspace,
609 * returning its value. Checks the length against the limit.
610 *
611 * @returns Pointer to the child string value, NULL if not found or no value.
612 * @param pcszPath Path to the child element. Slashes can be used to
613 * make a simple path to any decendant.
614 * @param cchValueLimit If the length of the returned value exceeds this
615 * limit a EIPRTFailure exception will be thrown.
616 * @param pcszNamespace The namespace to match, NULL (default) match any
617 * namespace. When using a path, this matches all
618 * elements along the way.
619 * @see findChildElement, findChildElementP
620 */
621 const char *findChildElementValuePN(const char *pcszPath, size_t cchValueLimit, const char *pcszNamespace = NULL) const
622 {
623 const ElementNode *pElem = findChildElementP(pcszPath, pcszNamespace);
624 if (pElem)
625 return pElem->getValueN(cchValueLimit);
626 return NULL;
627 }
628
629 /** Combines findChildElementNS and findAttributeValue.
630 *
631 * @returns Pointer to attribute string value, NULL if either the element or
632 * the attribute was not found.
633 * @param pcszChild The child element name.
634 * @param pcszAttribute The attribute name.
635 * @param pcszChildNamespace The namespace to match @a pcszChild with, NULL
636 * (default) match any namespace.
637 * @param pcszAttributeNamespace The namespace prefix to apply to the
638 * attribute, NULL (default) match any namespace.
639 * @see findChildElementNS and findAttributeValue
640 * @note The findChildElementAttributeValueP() method would do the same thing
641 * given the same inputs, but it would be slightly slower, thus the
642 * separate method.
643 */
644 const char *findChildElementAttributeValue(const char *pcszChild, const char *pcszAttribute,
645 const char *pcszChildNamespace = NULL,
646 const char *pcszAttributeNamespace = NULL) const
647 {
648 const ElementNode *pElem = findChildElementNS(pcszChildNamespace, pcszChild);
649 if (pElem)
650 return pElem->findAttributeValue(pcszAttribute, pcszAttributeNamespace);
651 return NULL;
652 }
653
654 /** Combines findChildElementP and findAttributeValue.
655 *
656 * @returns Pointer to attribute string value, NULL if either the element or
657 * the attribute was not found.
658 * @param pcszPath Path to the child element. Slashes can be used
659 * to make a simple path to any decendant.
660 * @param pcszAttribute The attribute name.
661 * @param pcszPathNamespace The namespace to match @a pcszPath with, NULL
662 * (default) match any namespace. When using a
663 * path, this matches all elements along the way.
664 * @param pcszAttributeNamespace The namespace prefix to apply to the
665 * attribute, NULL (default) match any namespace.
666 * @see findChildElementP and findAttributeValue
667 */
668 const char *findChildElementAttributeValueP(const char *pcszPath, const char *pcszAttribute,
669 const char *pcszPathNamespace = NULL,
670 const char *pcszAttributeNamespace = NULL) const
671 {
672 const ElementNode *pElem = findChildElementP(pcszPath, pcszPathNamespace);
673 if (pElem)
674 return pElem->findAttributeValue(pcszAttribute, pcszAttributeNamespace);
675 return NULL;
676 }
677
678 /** Combines findChildElementP and findAttributeValueN.
679 *
680 * @returns Pointer to attribute string value, NULL if either the element or
681 * the attribute was not found.
682 * @param pcszPath The attribute name. Slashes can be used to make a
683 * simple path to any decendant.
684 * @param pcszAttribute The attribute name.
685 * @param cchValueLimit If the length of the returned value exceeds this
686 * limit a EIPRTFailure exception will be thrown.
687 * @param pcszPathNamespace The namespace to match @a pcszPath with, NULL
688 * (default) match any namespace. When using a
689 * path, this matches all elements along the way.
690 * @param pcszAttributeNamespace The namespace prefix to apply to the
691 * attribute, NULL (default) match any namespace.
692 * @see findChildElementP and findAttributeValue
693 */
694 const char *findChildElementAttributeValuePN(const char *pcszPath, const char *pcszAttribute,
695 size_t cchValueLimit,
696 const char *pcszPathNamespace = NULL,
697 const char *pcszAttributeNamespace = NULL) const
698 {
699 const ElementNode *pElem = findChildElementP(pcszPath, pcszPathNamespace);
700 if (pElem)
701 return pElem->findAttributeValueN(pcszAttribute, cchValueLimit, pcszAttributeNamespace);
702 return NULL;
703 }
704
705
706 /** @name Tree enumeration.
707 * @{ */
708
709 /** Get the next tree element in a full tree enumeration.
710 *
711 * By starting with the root node, this can be used to enumerate the entire tree
712 * (or sub-tree if @a pElmRoot is used).
713 *
714 * @returns Pointer to the next element in the tree, NULL if we're done.
715 * @param pElmRoot The root of the tree we're enumerating. NULL if
716 * it's the entire tree.
717 */
718 ElementNode const *getNextTreeElement(ElementNode const *pElmRoot = NULL) const;
719 RT_CPP_GETTER_UNCONST_RET(ElementNode *, ElementNode, getNextTreeElement, (const ElementNode *pElmRoot = NULL), (pElmRoot))
720
721 /** Get the first child node.
722 * @returns Pointer to the first child node, NULL if no children. */
723 const Node *getFirstChild() const
724 {
725 return RTListGetFirstCpp(&m_children, const Node, m_listEntry);
726 }
727 RT_CPP_GETTER_UNCONST_RET(Node *, ElementNode, getFirstChild,(),())
728
729 /** Get the last child node.
730 * @returns Pointer to the last child node, NULL if no children. */
731 const Node *getLastChild() const
732 {
733 return RTListGetLastCpp(&m_children, const Node, m_listEntry);
734 }
735
736 /** Get the first child node.
737 * @returns Pointer to the first child node, NULL if no children. */
738 const ElementNode *getFirstChildElement() const;
739
740 /** Get the last child node.
741 * @returns Pointer to the last child node, NULL if no children. */
742 const ElementNode *getLastChildElement() const;
743
744 /** Get the previous sibling element.
745 * @returns Pointer to the previous sibling element, NULL if first child
746 * element.
747 * @see getNextSibilingElement, getPrevSibling
748 */
749 const ElementNode *getPrevSibilingElement() const;
750
751 /** Get the next sibling element.
752 * @returns Pointer to the next sibling element, NULL if last child element.
753 * @see getPrevSibilingElement, getNextSibling
754 */
755 const ElementNode *getNextSibilingElement() const;
756
757 /** Find the previous element matching the given name and namespace (optionally).
758 * @returns Pointer to the previous sibling element, NULL if first child
759 * element.
760 * @param pcszName The element name to match.
761 * @param pcszNamespace The namespace name, default is NULL which means
762 * anything goes.
763 * @note Changed the order of the arguments.
764 */
765 const ElementNode *findPrevSibilingElement(const char *pcszName, const char *pcszNamespace = NULL) const;
766
767 /** Find the next element matching the given name and namespace (optionally).
768 * @returns Pointer to the previous sibling element, NULL if first child
769 * element.
770 * @param pcszName The element name to match.
771 * @param pcszNamespace The namespace name, default is NULL which means
772 * anything goes.
773 * @note Changed the order of the arguments.
774 */
775 const ElementNode *findNextSibilingElement(const char *pcszName, const char *pcszNamespace = NULL) const;
776 /** @} */
777
778 /** @name Attribute enumeration
779 * @{ */
780
781 /** Get the first attribute node.
782 * @returns Pointer to the first child node, NULL if no attributes. */
783 const AttributeNode *getFirstAttribute() const
784 {
785 return RTListGetFirstCpp(&m_attributes, const AttributeNode, m_listEntry);
786 }
787
788 /** Get the last attribute node.
789 * @returns Pointer to the last child node, NULL if no attributes. */
790 const AttributeNode *getLastAttribute() const
791 {
792 return RTListGetLastCpp(&m_attributes, const AttributeNode, m_listEntry);
793 }
794
795 /** @} */
796
797 const AttributeNode *findAttribute(const char *pcszMatch, const char *pcszNamespace = NULL) const;
798 /** Find the first attribute with the given name, returning its value string.
799 * @returns Pointer to the attribute string value.
800 * @param pcszName The attribute name.
801 * @param pcszNamespace The namespace name, default is NULL which means
802 * anything goes.
803 * @see getAttributeValue
804 */
805 const char *findAttributeValue(const char *pcszName, const char *pcszNamespace = NULL) const
806 {
807 const AttributeNode *pAttr = findAttribute(pcszName, pcszNamespace);
808 if (pAttr)
809 return pAttr->getValue();
810 return NULL;
811 }
812 /** Find the first attribute with the given name, returning its value string.
813 * @returns Pointer to the attribute string value.
814 * @param pcszName The attribute name.
815 * @param cchValueLimit If the length of the returned value exceeds this
816 * limit a EIPRTFailure exception will be thrown.
817 * @param pcszNamespace The namespace name, default is NULL which means
818 * anything goes.
819 * @see getAttributeValue
820 */
821 const char *findAttributeValueN(const char *pcszName, size_t cchValueLimit, const char *pcszNamespace = NULL) const
822 {
823 const AttributeNode *pAttr = findAttribute(pcszName, pcszNamespace);
824 if (pAttr)
825 return pAttr->getValueN(cchValueLimit);
826 return NULL;
827 }
828
829 bool getAttributeValue(const char *pcszMatch, const char *&pcsz, const char *pcszNamespace = NULL) const
830 { return getAttributeValue(pcszMatch, &pcsz, pcszNamespace); }
831 bool getAttributeValue(const char *pcszMatch, RTCString &str, const char *pcszNamespace = NULL) const
832 { return getAttributeValue(pcszMatch, &str, pcszNamespace); }
833 bool getAttributeValuePath(const char *pcszMatch, RTCString &str, const char *pcszNamespace = NULL) const
834 { return getAttributeValue(pcszMatch, &str, pcszNamespace); }
835 bool getAttributeValue(const char *pcszMatch, int32_t &i, const char *pcszNamespace = NULL) const
836 { return getAttributeValue(pcszMatch, &i, pcszNamespace); }
837 bool getAttributeValue(const char *pcszMatch, uint32_t &i, const char *pcszNamespace = NULL) const
838 { return getAttributeValue(pcszMatch, &i, pcszNamespace); }
839 bool getAttributeValue(const char *pcszMatch, int64_t &i, const char *pcszNamespace = NULL) const
840 { return getAttributeValue(pcszMatch, &i, pcszNamespace); }
841 bool getAttributeValue(const char *pcszMatch, uint64_t &u, const char *pcszNamespace = NULL) const
842 { return getAttributeValue(pcszMatch, &u, pcszNamespace); }
843 bool getAttributeValue(const char *pcszMatch, bool &f, const char *pcszNamespace = NULL) const
844 { return getAttributeValue(pcszMatch, &f, pcszNamespace); }
845 bool getAttributeValueN(const char *pcszMatch, const char *&pcsz, size_t cchValueLimit, const char *pcszNamespace = NULL) const
846 { return getAttributeValueN(pcszMatch, &pcsz, cchValueLimit, pcszNamespace); }
847 bool getAttributeValueN(const char *pcszMatch, RTCString &str, size_t cchValueLimit, const char *pcszNamespace = NULL) const
848 { return getAttributeValueN(pcszMatch, &str, cchValueLimit, pcszNamespace); }
849 bool getAttributeValuePathN(const char *pcszMatch, RTCString &str, size_t cchValueLimit, const char *pcszNamespace = NULL) const
850 { return getAttributeValueN(pcszMatch, &str, cchValueLimit, pcszNamespace); }
851
852 /** @name Variants that for clarity does not use references for output params.
853 * @{ */
854 bool getAttributeValue(const char *pcszMatch, const char **ppcsz, const char *pcszNamespace = NULL) const;
855 bool getAttributeValue(const char *pcszMatch, RTCString *pStr, const char *pcszNamespace = NULL) const;
856 bool getAttributeValuePath(const char *pcszMatch, RTCString *pStr, const char *pcszNamespace = NULL) const;
857 bool getAttributeValue(const char *pcszMatch, int32_t *pi, const char *pcszNamespace = NULL) const;
858 bool getAttributeValue(const char *pcszMatch, uint32_t *pu, const char *pcszNamespace = NULL) const;
859 bool getAttributeValue(const char *pcszMatch, int64_t *piValue, const char *pcszNamespace = NULL) const;
860 bool getAttributeValue(const char *pcszMatch, uint64_t *pu, const char *pcszNamespace = NULL) const;
861 bool getAttributeValue(const char *pcszMatch, bool *pf, const char *pcszNamespace = NULL) const;
862 bool getAttributeValueN(const char *pcszMatch, const char **ppcsz, size_t cchValueLimit, const char *pcszNamespace = NULL) const;
863 bool getAttributeValueN(const char *pcszMatch, RTCString *pStr, size_t cchValueLimit, const char *pcszNamespace = NULL) const;
864 bool getAttributeValuePathN(const char *pcszMatch, RTCString *pStr, size_t cchValueLimit, const char *pcszNamespace = NULL) const;
865 /** @} */
866
867 /** @name Convenience methods for convering the element value.
868 * @{ */
869 bool getElementValue(int32_t *piValue) const;
870 bool getElementValue(uint32_t *puValue) const;
871 bool getElementValue(int64_t *piValue) const;
872 bool getElementValue(uint64_t *puValue) const;
873 bool getElementValue(bool *pfValue) const;
874 /** @} */
875
876 /** @name Convenience findChildElementValueP and getElementValue.
877 * @{ */
878 bool getChildElementValueP(const char *pcszPath, int32_t *piValue, const char *pcszNamespace = NULL) const
879 {
880 const ElementNode *pElem = findChildElementP(pcszPath, pcszNamespace);
881 return pElem && pElem->getElementValue(piValue);
882 }
883 bool getChildElementValueP(const char *pcszPath, uint32_t *puValue, const char *pcszNamespace = NULL) const
884 {
885 const ElementNode *pElem = findChildElementP(pcszPath, pcszNamespace);
886 return pElem && pElem->getElementValue(puValue);
887 }
888 bool getChildElementValueP(const char *pcszPath, int64_t *piValue, const char *pcszNamespace = NULL) const
889 {
890 const ElementNode *pElem = findChildElementP(pcszPath, pcszNamespace);
891 return pElem && pElem->getElementValue(piValue);
892 }
893 bool getChildElementValueP(const char *pcszPath, uint64_t *puValue, const char *pcszNamespace = NULL) const
894 {
895 const ElementNode *pElem = findChildElementP(pcszPath, pcszNamespace);
896 return pElem && pElem->getElementValue(puValue);
897 }
898 bool getChildElementValueP(const char *pcszPath, bool *pfValue, const char *pcszNamespace = NULL) const
899 {
900 const ElementNode *pElem = findChildElementP(pcszPath, pcszNamespace);
901 return pElem && pElem->getElementValue(pfValue);
902 }
903
904 /** @} */
905
906 /** @name Convenience findChildElementValueP and getElementValue with a
907 * default value being return if the child element isn't present.
908 *
909 * @remarks These will return false on conversion errors.
910 * @{ */
911 bool getChildElementValueDefP(const char *pcszPath, int32_t iDefault, int32_t *piValue, const char *pcszNamespace = NULL) const
912 {
913 const ElementNode *pElem = findChildElementP(pcszPath, pcszNamespace);
914 if (pElem)
915 return pElem->getElementValue(piValue);
916 *piValue = iDefault;
917 return true;
918 }
919 bool getChildElementValueDefP(const char *pcszPath, uint32_t uDefault, uint32_t *puValue, const char *pcszNamespace = NULL) const
920 {
921 const ElementNode *pElem = findChildElementP(pcszPath, pcszNamespace);
922 if (pElem)
923 return pElem->getElementValue(puValue);
924 *puValue = uDefault;
925 return true;
926 }
927 bool getChildElementValueDefP(const char *pcszPath, int64_t iDefault, int64_t *piValue, const char *pcszNamespace = NULL) const
928 {
929 const ElementNode *pElem = findChildElementP(pcszPath, pcszNamespace);
930 if (pElem)
931 return pElem->getElementValue(piValue);
932 *piValue = iDefault;
933 return true;
934 }
935 bool getChildElementValueDefP(const char *pcszPath, uint64_t uDefault, uint64_t *puValue, const char *pcszNamespace = NULL) const
936 {
937 const ElementNode *pElem = findChildElementP(pcszPath, pcszNamespace);
938 if (pElem)
939 return pElem->getElementValue(puValue);
940 *puValue = uDefault;
941 return true;
942 }
943 bool getChildElementValueDefP(const char *pcszPath, bool fDefault, bool *pfValue, const char *pcszNamespace = NULL) const
944 {
945 const ElementNode *pElem = findChildElementP(pcszPath, pcszNamespace);
946 if (pElem)
947 return pElem->getElementValue(pfValue);
948 *pfValue = fDefault;
949 return true;
950 }
951 /** @} */
952
953 ElementNode *createChild(const char *pcszElementName);
954
955 ContentNode *addContent(const char *pcszContent);
956 ContentNode *addContent(const RTCString &strContent)
957 {
958 return addContent(strContent.c_str());
959 }
960
961 ContentNode *setContent(const char *pcszContent);
962 ContentNode *setContent(const RTCString &strContent)
963 {
964 return setContent(strContent.c_str());
965 }
966
967 AttributeNode *setAttribute(const char *pcszName, const char *pcszValue);
968 AttributeNode *setAttribute(const char *pcszName, const RTCString &strValue)
969 {
970 return setAttribute(pcszName, strValue.c_str());
971 }
972 AttributeNode *setAttributePath(const char *pcszName, const RTCString &strValue);
973 AttributeNode *setAttribute(const char *pcszName, int32_t i);
974 AttributeNode *setAttribute(const char *pcszName, uint32_t i);
975 AttributeNode *setAttribute(const char *pcszName, int64_t i);
976 AttributeNode *setAttribute(const char *pcszName, uint64_t i);
977 AttributeNode *setAttributeHex(const char *pcszName, uint32_t i);
978 AttributeNode *setAttribute(const char *pcszName, bool f);
979
980 virtual ~ElementNode();
981
982protected:
983 // hide the default constructor so people use only our factory methods
984 ElementNode(const ElementNode *pElmRoot, Node *pParent, PRTLISTANCHOR pListAnchor, xmlNode *pLibNode);
985 ElementNode(const ElementNode &x); // no copying
986
987 /** We keep a pointer to the root element for attribute namespace handling. */
988 const ElementNode *m_pElmRoot;
989
990 /** List of child elements and content nodes. */
991 RTLISTANCHOR m_children;
992 /** List of attributes nodes. */
993 RTLISTANCHOR m_attributes;
994
995 static void buildChildren(ElementNode *pElmRoot);
996
997 friend class Node;
998 friend class Document;
999 friend class XmlFileParser;
1000};
1001
1002/**
1003 * Node subclass that represents content (non-element text).
1004 *
1005 * Since the Node constructor is private, one can create new content nodes
1006 * only through the following factory methods:
1007 *
1008 * -- ElementNode::addContent()
1009 */
1010class RT_DECL_CLASS ContentNode : public Node
1011{
1012public:
1013
1014protected:
1015 // hide the default constructor so people use only our factory methods
1016 ContentNode(Node *pParent, PRTLISTANCHOR pListAnchor, xmlNode *pLibNode);
1017 ContentNode(const ContentNode &x); // no copying
1018
1019 friend class Node;
1020 friend class ElementNode;
1021};
1022
1023
1024/**
1025 * Handy helper class with which one can loop through all or some children
1026 * of a particular element. See NodesLoop::forAllNodes() for details.
1027 */
1028class RT_DECL_CLASS NodesLoop
1029{
1030public:
1031 NodesLoop(const ElementNode &node, const char *pcszMatch = NULL);
1032 ~NodesLoop();
1033 const ElementNode* forAllNodes() const;
1034
1035private:
1036 /* Obscure class data */
1037 struct Data;
1038 Data *m;
1039};
1040
1041/**
1042 * The XML document class. An instance of this needs to be created by a user
1043 * of the XML classes and then passed to
1044 *
1045 * -- XmlMemParser or XmlFileParser to read an XML document; those classes then
1046 * fill the caller's Document with ElementNode, ContentNode and AttributeNode
1047 * instances. The typical sequence then is:
1048 * @code
1049 Document doc;
1050 XmlFileParser parser;
1051 parser.read("file.xml", doc);
1052 Element *pElmRoot = doc.getRootElement();
1053 @endcode
1054 *
1055 * -- XmlMemWriter or XmlFileWriter to write out an XML document after it has
1056 * been created and filled. Example:
1057 *
1058 * @code
1059 Document doc;
1060 Element *pElmRoot = doc.createRootElement();
1061 // add children
1062 xml::XmlFileWriter writer(doc);
1063 writer.write("file.xml", true);
1064 @endcode
1065 */
1066class RT_DECL_CLASS Document
1067{
1068public:
1069 Document();
1070 ~Document();
1071
1072 Document(const Document &x);
1073 Document& operator=(const Document &x);
1074
1075 const ElementNode* getRootElement() const;
1076 ElementNode* getRootElement();
1077
1078 ElementNode* createRootElement(const char *pcszRootElementName,
1079 const char *pcszComment = NULL);
1080
1081private:
1082 friend class XmlMemParser;
1083 friend class XmlFileParser;
1084 friend class XmlMemWriter;
1085 friend class XmlStringWriter;
1086 friend class XmlFileWriter;
1087
1088 void refreshInternals();
1089
1090 /* Obscure class data */
1091 struct Data;
1092 Data *m;
1093};
1094
1095/*
1096 * XmlParserBase
1097 *
1098 */
1099
1100class RT_DECL_CLASS XmlParserBase
1101{
1102protected:
1103 XmlParserBase();
1104 ~XmlParserBase();
1105
1106 xmlParserCtxtPtr m_ctxt;
1107};
1108
1109/*
1110 * XmlMemParser
1111 *
1112 */
1113
1114class RT_DECL_CLASS XmlMemParser : public XmlParserBase
1115{
1116public:
1117 XmlMemParser();
1118 ~XmlMemParser();
1119
1120 void read(const void* pvBuf, size_t cbSize, const RTCString &strFilename, Document &doc);
1121};
1122
1123/*
1124 * XmlFileParser
1125 *
1126 */
1127
1128class RT_DECL_CLASS XmlFileParser : public XmlParserBase
1129{
1130public:
1131 XmlFileParser();
1132 ~XmlFileParser();
1133
1134 void read(const RTCString &strFilename, Document &doc);
1135
1136private:
1137 /* Obscure class data */
1138 struct Data;
1139 struct Data *m;
1140
1141 static int ReadCallback(void *aCtxt, char *aBuf, int aLen) RT_NOTHROW_PROTO;
1142 static int CloseCallback(void *aCtxt) RT_NOTHROW_PROTO;
1143};
1144
1145/**
1146 * XmlMemWriter
1147 */
1148class RT_DECL_CLASS XmlMemWriter
1149{
1150public:
1151 XmlMemWriter();
1152 ~XmlMemWriter();
1153
1154 void write(const Document &doc, void** ppvBuf, size_t *pcbSize);
1155
1156private:
1157 void* m_pBuf;
1158};
1159
1160
1161/**
1162 * XmlStringWriter - writes the XML to an RTCString instance.
1163 */
1164class RT_DECL_CLASS XmlStringWriter
1165{
1166public:
1167 XmlStringWriter();
1168
1169 int write(const Document &rDoc, RTCString *pStrDst);
1170
1171private:
1172 static int WriteCallbackForSize(void *pvUser, const char *pachBuf, int cbToWrite) RT_NOTHROW_PROTO;
1173 static int WriteCallbackForReal(void *pvUser, const char *pachBuf, int cbToWrite) RT_NOTHROW_PROTO;
1174 static int CloseCallback(void *pvUser) RT_NOTHROW_PROTO;
1175
1176 /** Pointer to the destination string while we're in the write() call. */
1177 RTCString *m_pStrDst;
1178 /** Set by WriteCallback if we cannot grow the destination string. */
1179 bool m_fOutOfMemory;
1180};
1181
1182
1183/**
1184 * XmlFileWriter
1185 */
1186class RT_DECL_CLASS XmlFileWriter
1187{
1188public:
1189 XmlFileWriter(Document &doc);
1190 ~XmlFileWriter();
1191
1192 /**
1193 * Writes the XML document to the specified file.
1194 *
1195 * @param pcszFilename The name of the output file.
1196 * @param fSafe If @c true, some extra safety precautions will be
1197 * taken when writing the file:
1198 * -# The file is written with a '-tmp' suffix.
1199 * -# It is flushed to disk after writing.
1200 * -# Any original file is renamed to '-prev'.
1201 * -# The '-tmp' file is then renamed to the
1202 * specified name.
1203 * -# The directory changes are flushed to disk.
1204 * The suffixes are available via s_pszTmpSuff and
1205 * s_pszPrevSuff.
1206 */
1207 void write(const char *pcszFilename, bool fSafe);
1208
1209 static int WriteCallback(void *aCtxt, const char *aBuf, int aLen) RT_NOTHROW_PROTO;
1210 static int CloseCallback(void *aCtxt) RT_NOTHROW_PROTO;
1211
1212 /** The suffix used by XmlFileWriter::write() for the temporary file. */
1213 static const char * const s_pszTmpSuff;
1214 /** The suffix used by XmlFileWriter::write() for the previous (backup) file. */
1215 static const char * const s_pszPrevSuff;
1216
1217private:
1218 void writeInternal(const char *pcszFilename, bool fSafe);
1219
1220 /* Obscure class data */
1221 struct Data;
1222 Data *m;
1223};
1224
1225#if defined(_MSC_VER)
1226#pragma warning (default:4251)
1227#endif
1228
1229/** @} */
1230
1231} // end namespace xml
1232
1233#endif /* !IPRT_INCLUDED_cpp_xml_h */
1234
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette