]> xenbits.xensource.com Git - libvirt.git/commitdiff
util: introduce virXMLFormatElement helper
authorPavel Hrdina <phrdina@redhat.com>
Thu, 24 Aug 2017 13:08:23 +0000 (15:08 +0200)
committerPavel Hrdina <phrdina@redhat.com>
Mon, 28 Aug 2017 12:02:44 +0000 (14:02 +0200)
This helper allows you to better structurize the code if some element
may or may not contains attributes and/or child elements.

Reviewed-by: John Ferlan <jferlan@redhat.com>
Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
src/libvirt_private.syms
src/util/virxml.c
src/util/virxml.h

index b944bb4b2c66d24a2d3db787e54752ff243e761a..f30a04b145cb3ecab0edc4fbe7d72b8ce3f62800 100644 (file)
@@ -2956,6 +2956,7 @@ virVHBAPathExists;
 virXMLCheckIllegalChars;
 virXMLChildElementCount;
 virXMLExtractNamespaceXML;
+virXMLFormatElement;
 virXMLNodeContentString;
 virXMLNodeNameEqual;
 virXMLNodeSanitizeNamespaces;
index 562a4bf3bad44ce7c12267c80021d33b3c74c2cd..885f59bceb7268e9a8e5c29a2e1409badfd34e44 100644 (file)
@@ -1354,3 +1354,50 @@ virXMLValidatorFree(virXMLValidatorPtr validator)
     xmlRelaxNGFree(validator->rng);
     VIR_FREE(validator);
 }
+
+
+/**
+ * virXMLFormatElement
+ * @buf: the parent buffer where the element will be placed
+ * @name: the name of the element
+ * @attrBuf: buffer with attributes for element, may be NULL
+ * @childBuf: buffer with child elements, may be NULL
+ *
+ * Helper to format element where attributes or child elements
+ * are optional and may not be formatted.  If both @attrBuf and
+ * @childBuf are NULL or are empty buffers the element is not
+ * formatted.
+ *
+ * Returns 0 on success, -1 on error.
+ */
+int
+virXMLFormatElement(virBufferPtr buf,
+                    const char *name,
+                    virBufferPtr attrBuf,
+                    virBufferPtr childBuf)
+{
+    if ((!attrBuf || virBufferUse(attrBuf) == 0) &&
+        (!childBuf || virBufferUse(childBuf) == 0)) {
+        return 0;
+    }
+
+    if ((attrBuf && virBufferCheckError(attrBuf) < 0) ||
+        (childBuf && virBufferCheckError(childBuf) < 0)) {
+        return -1;
+    }
+
+    virBufferAsprintf(buf, "<%s", name);
+
+    if (attrBuf && virBufferUse(attrBuf) > 0)
+        virBufferAddBuffer(buf, attrBuf);
+
+    if (childBuf && virBufferUse(childBuf) > 0) {
+        virBufferAddLit(buf, ">\n");
+        virBufferAddBuffer(buf, childBuf);
+        virBufferAsprintf(buf, "</%s>\n", name);
+    } else {
+        virBufferAddLit(buf, "/>\n");
+    }
+
+    return 0;
+}
index 86baeb37a75113dd8237814d5c00a5550a7b216a..1a7d61a8bc2af491df5cc55138a26ae5080c72bb 100644 (file)
@@ -215,4 +215,10 @@ virXMLValidateAgainstSchema(const char *schemafile,
 void
 virXMLValidatorFree(virXMLValidatorPtr validator);
 
+int
+virXMLFormatElement(virBufferPtr buf,
+                    const char *name,
+                    virBufferPtr attrBuf,
+                    virBufferPtr childBuf);
+
 #endif                          /* __VIR_XML_H__ */