I am using GDataXML in my iOS application and want a simple way to format and print an XML string - "pretty print"
Does anyone know of an algorithm in Objective C, or one that works in another language I can translate?
Use your XML REST URL to Pretty XML and Print XML. Click on the URL button, Enter URL and Submit. Users can also xml pretty print the XML file by uploading the file. Pretty Print XML is alternative of Notepad++ / VSCode / Sublime to xml pretty print.
Pretty Print: Ctrl + Shift + Alt + B. Pretty Print (indent attributes): Ctrl + Shift + Alt + A.
What is XML? The Extensible Markup Language (XML) is a simple text-based format for representing structured information: documents, data, configuration, books, transactions, invoices, and much more. It was derived from an older standard format called SGML (ISO 8879), in order to be more suitable for Web use.
You can modify the source code of GDataXMLNode direcly:
- (NSString *)XMLString {
...
// enable formatting (pretty print / beautifier)
int format = 1; // changed from 0 to 1
...
}
Alternative:
As I didn't want to modify the library directly (for maintenance reasons), I wrote that category to extend the class from outside:
GDataXMLNode+PrettyFormatter.h:
#import "GDataXMLNode.h"
@interface GDataXMLNode (PrettyFormatter)
- (NSString *)XMLStringFormatted;
@end
GDataXMLNode+PrettyFormatter.m:
#import "GDataXMLNode+PrettyFormatter.h"
@implementation GDataXMLNode (PrettyFormatter)
- (NSString *)XMLStringFormatted {
NSString *str = nil;
if (xmlNode_ != NULL) {
xmlBufferPtr buff = xmlBufferCreate();
if (buff) {
xmlDocPtr doc = NULL;
int level = 0;
// enable formatting (pretty print / beautifier)
int format = 1;
int result = xmlNodeDump(buff, doc, xmlNode_, level, format);
if (result > -1) {
str = [[[NSString alloc] initWithBytes:(xmlBufferContent(buff))
length:(xmlBufferLength(buff))
encoding:NSUTF8StringEncoding] autorelease];
}
xmlBufferFree(buff);
}
}
// remove leading and trailing whitespace
NSCharacterSet *ws = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSString *trimmed = [str stringByTrimmingCharactersInSet:ws];
return trimmed;
}
@end
I've used HTML Tidy (http://tidy.sourceforge.net/) for things like this. It's a C library so can be linked in to and called from an Objective C runtime fairly easily as long as you're comfortable with C. The C++ API is callable from Objective C++ so that might be easier to use if you're comfortable with Objective C++.
I've not used the C or C++ bindings; I did it via Ruby or Python but it's all the same lib. It will read straight XML (as well as potentially dirty HTML) and it has both simple and pretty print options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With