IOS uses GDataXML-HTML to generate XML
XML classes that come with iOS versions can only be parsed and cannot be generated. Open-source library GDataXML-HTML not only supports XML parsing, but also supports generating XML.
1. Add GDataXML-HTML to the project.
All projects used by the author are hosted by Cocoapods. If you are not familiar with Cocoapods, refer to [cococoapods installation and use].
Add
pod 'GDataXML-HTML', '~> 1.1.0'
Run the following command to add the Library to the project:
pod update
2. Add the libxml header file location for the project
In the project configuration, add "Header Search Paths:
${SDK_ROOT}/usr/include/libxml2
3. Use GDataXML-HTML in the project
// Create a Tag element GDataXMLElement * element = [GDataXMLNode elementWithName: @ "user" stringValue: @ "will"]; // create an attribute GDataXMLElement * attribute = [GDataXMLNode attributeWithName: @ "a" stringValue: @ "B"]; // create a root tag GDataXMLElement * rootElement = [GDataXMLNode elementWithName: @ "root"]; // Add the tag and attribute to the root tag [rootElement addChild: element]; [rootElement addAttribute: attribute]; // generate the xml file content GDataXMLDocument * xmlDoc = [[GDataXMLDocument alloc] initWithRootElement: rootElement]; NSData * data = [xmlDoc XMLData]; NSString * xmlString = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "% @", xmlString );
The NSlog output content is:
will