Link to home
Start Free TrialLog in
Avatar of Harisha M G
Harisha M GFlag for India

asked on

Adding attribute to a parent element

Hi,

I am using libxml2 to generate XML files. In the attached code, I am expecting output to be like:

<TAG_A ATTR_A1="Val1"  ATTR_A2="Val3">
      <TAG_B ATTR_B="Val2"/>
</TAG_A>

But it is not able to add attribute to the parent, and is giving output as:

<TAG_A ATTR_A1="Val1">
      <TAG_B ATTR_B="Val2"/>
</TAG_A>

That is, ATTR_A2 is missing for the element TAG_A. Is there any other API/work around to solve this problem?
#include <libxml/xmlwriter.h>

int main(int argc, char *argv[])
{
    xmlTextWriterPtr writer;
    writer =xmlNewTextWriterFilename("test.xml", 0);
    xmlTextWriterStartElement(writer, "TAG_A");
    xmlTextWriterWriteFormatAttribute(writer, BAD_CAST "ATTR_A1", "Val1");
    xmlTextWriterStartElement(writer, "TAG_B");
    xmlTextWriterWriteFormatAttribute(writer, BAD_CAST "ATTR_B", "Val2");

    xmlTextWriterEndElement(writer);
    xmlTextWriterWriteFormatAttribute(writer, BAD_CAST "ATTR_A2", "Val3");
    xmlTextWriterEndElement(writer);
    xmlFreeTextWriter(writer);
}

Open in new window

Avatar of Deepu Abraham
Deepu Abraham
Flag of United States of America image

Try using
xmlTextWriterStartAttribute();

have a look at this:
http://xmlsoft.org/html/libxml-xmlwriter.html
Avatar of Harisha M G

ASKER

I tried that function this way, but it is not working:
#include <libxml/xmlwriter.h>

int main(int argc, char *argv[])
{
    xmlTextWriterPtr writer;
    writer =xmlNewTextWriterFilename("test.xml", 0);
    xmlTextWriterStartElement(writer, "TAG_A");
    xmlTextWriterWriteFormatAttribute(writer, BAD_CAST "ATTR_A1", "Val1");
    xmlTextWriterStartElement(writer, "TAG_B");
    xmlTextWriterWriteFormatAttribute(writer, BAD_CAST "ATTR_B", "Val2");

    xmlTextWriterEndElement(writer);
    xmlTextWriterStartAttribute(writer, BAD_CAST "ATTR_A2");
    xmlTextWriterEndElement(writer);
    xmlFreeTextWriter(writer);
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Harisha M G
Harisha M G
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
There is not solution for this. Answer is "it can't be done", as I have posted. Please accept my comment solution and make it PAQ
I found through practical experience that it can't be done