我在我的 iOS 应用程序中使用 GDataXML,并且想要一种简单的方法来格式化和打印 XML 字符串 - “漂亮打印”
有谁知道 Objective C 中的算法,或者我可以翻译的另一种语言的算法?
我在我的 iOS 应用程序中使用 GDataXML,并且想要一种简单的方法来格式化和打印 XML 字符串 - “漂亮打印”
有谁知道 Objective C 中的算法,或者我可以翻译的另一种语言的算法?
您可以直接修改 GDataXMLNode 的源代码:
- (NSString *)XMLString {
...
// enable formatting (pretty print / beautifier)
int format = 1; // changed from 0 to 1
...
}
选择:
由于我不想直接修改库(出于维护原因),我编写了该类别以从外部扩展该类:
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.