简体   繁体   中英

Libxml2: Outputting XML element with attribute and content

I'm using the libxml2 XMLTextWriter API (of which an official example is provided here ) to output XML, but can't find any examples or see how to produce an element with both attributes and content, like so:

 <MyElement myAttrib="x">Content</MyElement>

Surprisingly, I'm not seeing any questions on SO that address this. Maybe because people just output XML themselves rather than using a library.

The C code I have so far is:

if (xmlTextWriterStartElement(writer, BAD_CAST "MyElement") < 0
    || xmlTextWriterWriteAttribute(writer, BAD_CAST "myAttrib", "x") < 0
    || somehow print out content < 0
    || xmlTextWriterEndElement(writer) < 0)
{
   // Handle error
}

It looks like xmlTextWriterWriteFormatString or xmlTextWriterWriteString will do the trick. Somehow I missed those at first when looking through the API details.

Rather than delete, I'll leave here as this info might be useful for others looking for this info quickly.

Example:

if (xmlTextWriterStartElement(writer, BAD_CAST "MyElement") < 0
    || xmlTextWriterWriteAttribute(writer, BAD_CAST "myAttrib", "x") < 0
    || xmlTextWriterWriteString(writer, "Content") < 0
    || xmlTextWriterEndElement(writer) < 0)
{
   // Handle error
}

Update: Tested and confirmed this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM