浏览代码

fix various parts of haxe.xml.Printer

Simon Krajewski 11 年之前
父节点
当前提交
855a197654
共有 1 个文件被更改,包括 22 次插入11 次删除
  1. 22 11
      std/haxe/xml/Printer.hx

+ 22 - 11
std/haxe/xml/Printer.hx

@@ -30,16 +30,18 @@ package haxe.xml;
 
 class Printer {
 
-	static public function print(xml:Xml) {
-		var printer = new Printer();
+	static public function print(xml:Xml, ?pretty = false) {
+		var printer = new Printer(pretty);
 		printer.writeNode(xml, "");
 		return printer.output.toString();
 	}
 
 	var output:StringBuf;
+	var pretty:Bool;
 
-	function new() {
+	function new(pretty) {
 		output = new StringBuf();
+		this.pretty = pretty;
 	}
 
 	function writeNode(value:Xml, tabs:String) {
@@ -52,6 +54,7 @@ class Printer {
 			case Xml.Comment:
 				var commentContent:String = value.nodeValue;
 				commentContent = ~/[\n\r\t]+/g.replace(commentContent, "");
+				commentContent = "<!--" + commentContent + "-->";
 				write(tabs);
 				write(StringTools.trim(commentContent));
 				newline();
@@ -71,23 +74,28 @@ class Printer {
 					write(">");
 					newline();
 					for (child in value) {
-						writeNode(child, tabs + "\t");
+						writeNode(child, pretty ? tabs + "\t" : tabs);
 					}
 					write(tabs + "</");
 					write(value.nodeName);
 					write(">");
 					newline();
 				} else {
-					write(" />");
+					write("/>");
 					newline();
 				}
-		case Xml.PCData:
-			var nodeValue:String = StringTools.trim(value.nodeValue);
+			case Xml.PCData:
+				var nodeValue:String = value.nodeValue;
 				if (nodeValue.length != 0) {
 					write(tabs + nodeValue);
 					newline();
 				}
-			}
+			case Xml.ProcessingInstruction:
+				write("<?" + value.nodeValue + "?>");
+			case Xml.DocType:
+				write("<!DOCTYPE " + value.nodeValue + ">");
+			case _:
+		}
 	}
 
 	inline function write(input:String) {
@@ -95,18 +103,21 @@ class Printer {
 	}
 
 	inline function newline() {
-		output.add("\n");
+		if (pretty) {
+			output.add("");
+		}
 	}
 
 	function hasChildren(value:Xml):Bool {
 		for (child in value) {
 			switch (child.nodeType) {
-				case Xml.Element:
+				case Xml.Element, Xml.PCData:
 					return true;
-				case Xml.CData, Xml.Comment, Xml.PCData:
+				case Xml.CData, Xml.Comment:
 					if (StringTools.ltrim(child.nodeValue).length != 0) {
 						return true;
 					}
+				case _:
 			}
 		}
 		return false;