How to generate XML file using libxml2?

2019-04-13 05:30发布

问题:

I have downloaded libxml2 from xmlsoft.org. I used this for parsing an xml file. Now I want to create my own xml file using the same libxml like this...

<?xml version="1.0"?>
<Powersettings>
<PowerScheme>Testing</PowerScheme>
<CPUSpeed>Adaptive</CPUSpeed>
<Screensaver>No</Screensaver>
<LockScreentime>0</LockScreentime>
<Shutdownflag>Yes</Shutdownflag>
<DownloadsFlag>No</DownloadsFlag>
<PPasswordprotected>No</PPasswordprotected>
<Appsensorname>(None)</Appsensorname>
</Powersettings>

I am using gcc compiler, C language to write program and whole data is in a Structure. I'm looking for a Good tutorial or an example program to create xml document as above using libxml2.

Any help ?

回答1:

Based on http://xmlsoft.org/examples/testWriter.c -- disclaimer: I have never used libxml2, haven't tested it, and there's no error detection:

xmlTextWriterPtr writer;
writer = xmlNewTextWriterFilename("test.xml", 0);
xmlTextWriterStartDocument(writer, NULL, "UTF-8", NULL);
xmlTextWriterStartElement(writer, "Powersettings");
xmlTextWriterWriteElement(writer, "PowerScheme", "Testing"); xmlTextWriterEndElement(writer);
xmlTextWriterWriteElement(writer, "CPUSpeed", "Adaptive"); xmlTextWriterEndElement(writer);
/* ... etc ... */
xmlTextWriterEndElement(writer);
xmlTextWriterEndDocument(writer);
xmlFreeTextWriter(writer);


标签: xsd libxml2 xml