struct xml_writer_private {
FILE *fh;
+ ssize_t depth;
xmlTextWriterPtr xw;
xmlDocPtr doc;
};
if (xmlTextWriterWriteFormatAttribute(p->xw, BAD_CAST "label", "%s", descr) < 0)
log_warnx("lldpctl", "cannot add attribute 'label' to element %s", tag);
}
+
+ p->depth++;
}
void xml_attr(struct writer *w, const char *tag, const char *descr, const char *value ) {
log_warnx("lldpctl", "cannot add '%s' as data to element", data?data:"(none)");
}
+void xml_new_writer(struct xml_writer_private *priv)
+{
+ priv->xw = xmlNewTextWriterDoc(&(priv->doc), 0);
+ if (!priv->xw)
+ fatalx("lldpctl", "cannot create xml writer");
+
+ xmlTextWriterSetIndent(priv->xw, 4);
+
+ if (xmlTextWriterStartDocument(priv->xw, NULL, "UTF-8", NULL) < 0 )
+ fatalx("lldpctl", "cannot start xml document");
+}
+
void xml_end(struct writer *w) {
struct xml_writer_private *p = w->priv;
if (xmlTextWriterEndElement(p->xw) < 0 )
log_warnx("lldpctl", "cannot end element");
-}
-#define MY_ENCODING "UTF-8"
+ if (--p->depth == 0) {
+ int failed = 0;
-void xml_finish(struct writer *w) {
- struct xml_writer_private *p = w->priv;
- int failed = 0;
+ if (xmlTextWriterEndDocument(p->xw) < 0 ) {
+ log_warnx("lldpctl", "cannot finish document");
+ failed = 1;
+ }
- if (xmlTextWriterEndDocument(p->xw) < 0 ) {
- log_warnx("lldpctl", "cannot finish document");
- failed = 1;
- }
+ xmlFreeTextWriter(p->xw);
- xmlFreeTextWriter(p->xw);
+ if (!failed)
+ xmlDocDump(p->fh, p->doc);
- if (!failed)
- xmlDocDump(p->fh, p->doc);
+ xmlFreeDoc(p->doc);
- xmlFreeDoc(p->doc);
+ xml_new_writer(p);
+ }
+}
+
+void xml_finish(struct writer *w) {
+ struct xml_writer_private *p = w->priv;
+ if (p->depth != 0) {
+ log_warnx("lldpctl", "unbalanced tags");
+ /* memory leak... */
+ }
free(w->priv);
free(w);
struct xml_writer_private *priv;
priv = malloc(sizeof(*priv));
- priv->fh = fh;
if (!priv) {
fatalx("lldpctl", "out of memory");
return NULL;
}
+ priv->fh = fh;
+ priv->depth = 0;
- priv->xw = xmlNewTextWriterDoc(&(priv->doc), 0);
- if (!priv->xw) {
- fatalx("lldpctl", "cannot create xml writer");
- return NULL;
- }
-
- xmlTextWriterSetIndent(priv->xw, 4);
-
- if (xmlTextWriterStartDocument(priv->xw, NULL, MY_ENCODING, NULL) < 0 ) {
- fatalx("lldpctl", "cannot start xml document");
- return NULL;
- }
+ xml_new_writer(priv);
result = malloc(sizeof(struct writer));
- if (!result) {
+ if (!result)
fatalx("lldpctl", "out of memory");
- return NULL;
- }
result->priv = priv;
result->start = xml_start;