XMLPrinter.java 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. // Copyright (c) 2001, 2003, 2005, 2006 Per M.A. Bothner and Brainfood Inc.
  2. // This is free software; for terms and warranty disclaimer see ./COPYING.
  3. package gnu.xml;
  4. import gnu.lists.*;
  5. import java.io.*;
  6. import gnu.lists.PrintConsumer;
  7. import gnu.math.RealNum;
  8. import gnu.kawa.io.PrettyWriter;
  9. import gnu.kawa.io.OutPort;
  10. import gnu.kawa.io.Path;
  11. import gnu.mapping.ThreadLocation;
  12. import gnu.mapping.Symbol;
  13. import gnu.text.Char;
  14. import gnu.text.Lexer;
  15. import java.math.BigDecimal;
  16. import gnu.expr.Keyword;
  17. import gnu.kawa.xml.XmlNamespace;
  18. /** Print an event stream in XML format on a PrintWriter. */
  19. public class XMLPrinter extends PrintConsumer
  20. implements PositionConsumer, XConsumer
  21. {
  22. protected int printIndent = -1;
  23. /** When indenting, should attributes be lined up? */
  24. public boolean indentAttributes;
  25. boolean printXMLdecl = false;
  26. public void setPrintXMLdecl (boolean value) { printXMLdecl = value; }
  27. boolean inDocument;
  28. boolean inAttribute = false;
  29. boolean inStartTag = false;
  30. /** 0: not in comment; 1: in comment normal; 2: in comment after '-'. */
  31. int inComment;
  32. boolean needXMLdecl = false;
  33. boolean canonicalize = true;
  34. public boolean canonicalizeCDATA;
  35. /** Handling of empty elements.
  36. * 0: No element element tags, as required for canonical XML:
  37. * {@code <br></br>}.
  38. * 1: Use XML-style empty element tags: {@code <br/>}
  39. * 2: Use HTML-compatible empty element tags: {@code <br />} but {@code <p></p>}.
  40. */
  41. public int useEmptyElementTag = 2;
  42. public boolean escapeText = true;
  43. public boolean escapeNonAscii = true;
  44. boolean isHtml = false;
  45. boolean isHtmlOrXhtml = false;
  46. boolean undeclareNamespaces = false;
  47. Object style;
  48. public boolean extended = true;
  49. /** Fluid parameter to control whether a DOCTYPE declaration is emitted.
  50. * If non-null, this is the the public identifier. */
  51. public static final ThreadLocation doctypeSystem
  52. = new ThreadLocation("doctype-system");
  53. /** The system identifier emitted in a DOCTYPE declaration.
  54. * Has no effect if doctypeSystem returns null.
  55. * If non-null, this is the the system identifier. */
  56. public static final ThreadLocation doctypePublic
  57. = new ThreadLocation("doctype-public");
  58. public static final ThreadLocation<String> indentLoc
  59. = new ThreadLocation<String>("xml-indent");
  60. /** Chain of currently active namespace nodes. */
  61. NamespaceBinding namespaceBindings = NamespaceBinding.predefinedXML;
  62. /** Stack of namespaceBindings as of active startElement calls. */
  63. NamespaceBinding[] namespaceSaveStack = new NamespaceBinding[20];
  64. Object[] elementNameStack = new Object[20];
  65. /** Difference between number of startElement and endElement calls so far. */
  66. int elementNesting;
  67. /* If prev==WORD, last output was a number or similar. */
  68. private static final int WORD = -2;
  69. private static final int ELEMENT_START = -3;
  70. private static final int ELEMENT_END = -4;
  71. private static final int COMMENT = -5;
  72. private static final int KEYWORD = -6;
  73. private static final int PROC_INST = -7;
  74. int prev = ' ';
  75. char savedHighSurrogate; // should perhaps be combined with prev?
  76. public XMLPrinter (Writer out, boolean autoFlush)
  77. {
  78. super(out, autoFlush);
  79. }
  80. public XMLPrinter (Writer out)
  81. {
  82. super(out);
  83. }
  84. public XMLPrinter(Consumer out) {
  85. super(out, false);
  86. }
  87. public XMLPrinter(PrintConsumer out) {
  88. super((Writer) out, false);
  89. }
  90. public XMLPrinter (OutputStream out)
  91. {
  92. super(new OutputStreamWriter(out));
  93. }
  94. public static XMLPrinter make(Consumer out, Object style)
  95. {
  96. XMLPrinter xout = new XMLPrinter(out);
  97. xout.setStyle(style);
  98. return xout;
  99. }
  100. /** Convert argument to string in XML syntax. */
  101. public static String toString (Object value)
  102. {
  103. StringWriter stringWriter = new StringWriter();
  104. new XMLPrinter(stringWriter).writeObject(value);
  105. return stringWriter.toString();
  106. }
  107. public void setStyle (Object style)
  108. {
  109. this.style = style;
  110. useEmptyElementTag = canonicalize ? 0 : 1;
  111. if ("html".equals(style))
  112. {
  113. isHtml = true;
  114. isHtmlOrXhtml = true;
  115. useEmptyElementTag = 2;
  116. // Pre-establish the html namespace, so it doesn't get printed.
  117. if (namespaceBindings == NamespaceBinding.predefinedXML)
  118. namespaceBindings = XmlNamespace.HTML_BINDINGS;
  119. }
  120. else if (namespaceBindings == XmlNamespace.HTML_BINDINGS)
  121. namespaceBindings = NamespaceBinding.predefinedXML;
  122. if ("xhtml".equals(style))
  123. {
  124. isHtmlOrXhtml = true;
  125. useEmptyElementTag = 2;
  126. }
  127. if ("plain".equals(style))
  128. escapeText = false;
  129. }
  130. public void setEscapeText(boolean v) { escapeText = v; }
  131. public void setEscapeNonAscii(boolean v) { escapeNonAscii = v; }
  132. public void setCanonicalizeCDATA(boolean v) { canonicalizeCDATA = v; }
  133. public void setUseEmptyElementTag(int v) { useEmptyElementTag = v; }
  134. public void setExtended(boolean v) { extended = v; }
  135. /** Controls whether to add extra indentation.
  136. * -1: don't add indentation; 0: pretty-print (avoid needless newlines);
  137. * 1: indent (force). */
  138. public void setIndent(int v) { printIndent = v; }
  139. boolean mustHexEscape (int v)
  140. {
  141. return (v >= 127 && (v <= 159 || escapeNonAscii))
  142. || v == 0x2028
  143. // We must escape control characters in attributes,
  144. // since otherwise they get normalized to ' '.
  145. || (v < ' ' && (inAttribute || (v != '\t' && v != '\n')));
  146. }
  147. public void write(int v) {
  148. closeTag();
  149. if (printIndent >= 0) {
  150. if ((v == '\r' || v == '\n')) {
  151. if (v != '\n' || prev != '\r')
  152. writeBreak(PrettyWriter.NEWLINE_MANDATORY);
  153. if (inComment > 0)
  154. inComment = 1;
  155. return;
  156. }
  157. }
  158. if (! escapeText) {
  159. writeRaw(v);
  160. prev = v;
  161. } else if (inComment > 0) {
  162. if (v == '-') {
  163. if (inComment == 1)
  164. inComment = 2;
  165. else
  166. writeRaw(' ');
  167. }
  168. else
  169. inComment = 1;
  170. writeRaw(v);
  171. } else {
  172. prev = ';';
  173. if (v == '<' && ! (isHtml && inAttribute))
  174. writeRaw("&lt;");
  175. else if (v == '>')
  176. writeRaw("&gt;");
  177. else if (v == '&')
  178. writeRaw("&amp;");
  179. else if (v == '\"' && inAttribute)
  180. writeRaw("&quot;");
  181. else if (mustHexEscape(v)) {
  182. int i = v;
  183. if (v >= 0xD800) {
  184. if (v < 0xDC00) {
  185. savedHighSurrogate = (char) v;
  186. return;
  187. } else if (v < 0xE000) { // low surrogate
  188. //if (highSurrogate < 0xDC00 || highSurrogate > 0xE000)
  189. // error();
  190. i = (savedHighSurrogate - 0xD800) * 0x400
  191. + (i - 0xDC00) + 0x10000;
  192. savedHighSurrogate = 0;
  193. }
  194. }
  195. writeRaw("&#x"+Integer.toHexString(i).toUpperCase()+";");
  196. } else {
  197. writeRaw(v);
  198. prev = v;
  199. }
  200. }
  201. }
  202. private void startWord()
  203. {
  204. closeTag();
  205. writeWordStart();
  206. }
  207. public void writeBoolean(boolean v)
  208. {
  209. startWord();
  210. super.print(v);
  211. writeWordEnd();
  212. }
  213. protected void startNumber()
  214. {
  215. startWord();
  216. }
  217. protected void endNumber()
  218. {
  219. writeWordEnd();
  220. }
  221. public void closeTag()
  222. {
  223. if (inStartTag && ! inAttribute)
  224. {
  225. if (printIndent >= 0 && indentAttributes)
  226. endLogicalBlock("");
  227. writeRaw(">");
  228. inStartTag = false;
  229. prev = ELEMENT_START;
  230. }
  231. else if (needXMLdecl)
  232. {
  233. // should also include encoding declaration FIXME.
  234. writeRaw("<?xml version=\"1.0\"?>\n");
  235. if (printIndent >= 0)
  236. {
  237. startLogicalBlock("", "", 2);
  238. }
  239. needXMLdecl = false;
  240. prev = '>';
  241. }
  242. }
  243. void setIndentMode ()
  244. {
  245. Object xmlIndent = indentLoc.get(null);
  246. String indent = xmlIndent == null ? null : xmlIndent.toString();
  247. if (indent == null)
  248. printIndent = -1;
  249. else if (indent.equals("pretty"))
  250. printIndent = 0;
  251. else if (indent.equals("always") || indent.equals("yes"))
  252. printIndent = 1;
  253. else // if (ident.equals("no")) or default:
  254. printIndent = -1;
  255. }
  256. public void startDocument()
  257. {
  258. if (printXMLdecl)
  259. {
  260. // We should emit an XML declaration, but don't emit it yet, in case
  261. // we get it later as a processing instruction.
  262. needXMLdecl = true;
  263. }
  264. setIndentMode();
  265. inDocument = true;
  266. if (printIndent >= 0 && ! needXMLdecl)
  267. startLogicalBlock("", "", 2);
  268. }
  269. public void endDocument()
  270. {
  271. inDocument = false;
  272. if (printIndent >= 0)
  273. endLogicalBlock("");
  274. freshLine();
  275. }
  276. public void beginEntity (Object base)
  277. {
  278. }
  279. public void endEntity ()
  280. {
  281. }
  282. protected void writeQName(Object name) {
  283. if (name instanceof Symbol) {
  284. Symbol sname = (Symbol) name;
  285. String prefix = sname.getPrefix();
  286. if (prefix != null && prefix.length() > 0) {
  287. writeRaw(prefix);
  288. writeRaw(':');
  289. }
  290. writeRaw(sname.getLocalPart());
  291. }
  292. else
  293. writeRaw(name == null ? "{null name}" : (String) name);
  294. }
  295. /** Write DOCTYPE using ThreadLocations doctypeSystem and doctypePublic */
  296. public void writeDoctypeIfDefined (String tagname)
  297. {
  298. Object systemIdentifier = doctypeSystem.get(null);
  299. if (systemIdentifier != null)
  300. {
  301. String systemId = systemIdentifier.toString();
  302. if (systemId.length() > 0)
  303. {
  304. Object publicIdentifier = doctypePublic.get(null);
  305. String publicId = publicIdentifier == null ? null
  306. : publicIdentifier.toString();
  307. writeDoctype(tagname, systemId, publicId);
  308. }
  309. }
  310. }
  311. public void writeDoctype(String tagname, String systemId, String publicId)
  312. {
  313. writeRaw("<!DOCTYPE ");
  314. writeRaw(tagname);
  315. if (publicId != null && publicId.length() > 0) {
  316. writeRaw(" PUBLIC \"");
  317. writeRaw(publicId);
  318. writeRaw("\" \"");
  319. } else {
  320. writeRaw(" SYSTEM \"");
  321. }
  322. writeRaw(systemId);
  323. writeRaw("\">");
  324. println();
  325. }
  326. public void startElement(Object type)
  327. {
  328. closeTag();
  329. if (elementNesting == 0)
  330. {
  331. if (! inDocument)
  332. setIndentMode();
  333. if (prev == PROC_INST)
  334. write('\n');
  335. if (type != null)
  336. writeDoctypeIfDefined(type.toString());
  337. }
  338. if (printIndent >= 0)
  339. {
  340. if (prev == ELEMENT_START || prev == ELEMENT_END || prev == COMMENT)
  341. writeBreak(printIndent > 0 ? PrettyWriter.NEWLINE_MANDATORY
  342. : PrettyWriter.NEWLINE_LINEAR);
  343. startLogicalBlock("", "", 2);
  344. }
  345. writeRaw('<');
  346. writeQName(type);
  347. if (printIndent >= 0 && indentAttributes)
  348. startLogicalBlock("", "", 2);
  349. elementNameStack[elementNesting] = type;
  350. NamespaceBinding elementBindings = null;
  351. namespaceSaveStack[elementNesting++] = namespaceBindings;
  352. if (type instanceof XName)
  353. {
  354. elementBindings = ((XName) type).namespaceNodes;
  355. NamespaceBinding join
  356. = NamespaceBinding.commonAncestor(elementBindings, namespaceBindings);
  357. int numBindings = elementBindings == null ? 0
  358. : elementBindings.count(join);
  359. NamespaceBinding[] sortedBindings = new NamespaceBinding[numBindings];
  360. int i = 0;
  361. boolean sortNamespaces = canonicalize;
  362. check_namespaces:
  363. for (NamespaceBinding ns = elementBindings; ns != join; ns = ns.next)
  364. {
  365. int j = i;
  366. boolean skip = false;
  367. String uri = ns.getUri();
  368. String prefix = ns.getPrefix();
  369. while (--j >= 0)
  370. {
  371. NamespaceBinding ns_j = sortedBindings[j];
  372. // If (compare(ns, ns_j) <= 0) break:
  373. String prefix_j = ns_j.getPrefix();
  374. if (prefix == prefix_j)
  375. continue check_namespaces;
  376. // If we're not canonicalizing, we just want to suppress
  377. // duplicates, rather than putting them in order.
  378. // Note we put the bindings in reverse order, since that's
  379. // what the following print loop expects.
  380. if (! sortNamespaces)
  381. continue;
  382. if (prefix == null)
  383. break;
  384. if (prefix_j != null && prefix.compareTo(prefix_j) <= 0)
  385. break;
  386. sortedBindings[j+1] = ns_j;
  387. }
  388. if (sortNamespaces)
  389. j++;
  390. else
  391. j = i;
  392. sortedBindings[j] = ns;
  393. i++;
  394. }
  395. numBindings = i;
  396. // Note we print the bindings in reverse order, since the chain
  397. // is in reverse document order.
  398. for (i = numBindings; --i >= 0; )
  399. {
  400. NamespaceBinding ns = sortedBindings[i];
  401. String prefix = ns.prefix;
  402. String uri = ns.uri;
  403. if (uri == namespaceBindings.resolve(prefix))
  404. // A matching namespace declaration is already in scope.
  405. continue;
  406. if (uri == null && prefix != null && ! undeclareNamespaces)
  407. continue;
  408. writeRaw(' '); // prettyprint break
  409. if (prefix == null)
  410. writeRaw("xmlns");
  411. else
  412. {
  413. writeRaw("xmlns:");
  414. writeRaw(prefix);
  415. }
  416. writeRaw("=\"");
  417. inAttribute = true;
  418. if (uri != null)
  419. write(uri);
  420. inAttribute = false;
  421. writeRaw('\"');
  422. }
  423. if (undeclareNamespaces)
  424. {
  425. // As needed emit namespace undeclarations as in
  426. // the XML Namespaces 1.1 Candidate Recommendation.
  427. // Most commonly this loop will run zero times.
  428. for (NamespaceBinding ns = namespaceBindings;
  429. ns != join; ns = ns.next)
  430. {
  431. String prefix = ns.prefix;
  432. if (ns.uri != null && elementBindings.resolve(prefix) == null)
  433. {
  434. writeRaw(' '); // prettyprint break
  435. if (prefix == null)
  436. writeRaw("xmlns");
  437. else
  438. {
  439. writeRaw("xmlns:");
  440. writeRaw(prefix);
  441. }
  442. writeRaw("=\"\"");
  443. }
  444. }
  445. }
  446. namespaceBindings = elementBindings;
  447. }
  448. if (elementNesting >= namespaceSaveStack.length)
  449. {
  450. NamespaceBinding[] nstmp = new NamespaceBinding[2 * elementNesting];
  451. System.arraycopy(namespaceSaveStack, 0, nstmp, 0, elementNesting);
  452. namespaceSaveStack = nstmp;
  453. Object[] nmtmp = new Object[2 * elementNesting];
  454. System.arraycopy(elementNameStack, 0, nmtmp, 0, elementNesting);
  455. elementNameStack = nmtmp;
  456. }
  457. inStartTag = true;
  458. if (isHtml) {
  459. String typeName = getHtmlTag(type);
  460. if ("script".equals(typeName) || "style".equals(typeName))
  461. escapeText = false;
  462. }
  463. }
  464. static final String HtmlEmptyTags
  465. = "/area/base/basefont/br/col/command/embed/frame/hr/img/input/isindex/keygen/link/meta/para/param/source/track/wbr/";
  466. public static boolean isHtmlEmptyElementTag(String name)
  467. {
  468. int index = HtmlEmptyTags.indexOf(name);
  469. return index > 0 && HtmlEmptyTags.charAt(index-1) == '/'
  470. && HtmlEmptyTags.charAt(index+name.length()) == '/';
  471. }
  472. protected String getHtmlTag (Object type)
  473. {
  474. if (type instanceof Symbol)
  475. {
  476. Symbol sym = (Symbol) type;
  477. String uri = sym.getNamespaceURI();
  478. if (uri == XmlNamespace.XHTML_NAMESPACE
  479. || (isHtmlOrXhtml && uri == ""))
  480. return sym.getLocalPart();
  481. }
  482. else if (isHtmlOrXhtml)
  483. return type.toString();
  484. return null;
  485. }
  486. public void endElement ()
  487. {
  488. if (useEmptyElementTag == 0)
  489. closeTag();
  490. Object type = elementNameStack[elementNesting-1];
  491. // typeName is only used for checking certain HTML tags.
  492. String typeName = getHtmlTag(type);
  493. if (inStartTag)
  494. {
  495. if (printIndent >= 0 && indentAttributes)
  496. {
  497. endLogicalBlock("");
  498. }
  499. String end = null;
  500. boolean isEmpty = typeName != null && isHtmlEmptyElementTag(typeName);
  501. if (useEmptyElementTag == 0
  502. || (typeName != null && ! isEmpty))
  503. {
  504. if (type instanceof Symbol)
  505. {
  506. Symbol sym = (Symbol) type;
  507. String prefix = sym.getPrefix();
  508. String uri = sym.getNamespaceURI();
  509. String local = sym.getLocalName();
  510. if (prefix != "")
  511. end = "></"+prefix+":"+local+">";
  512. else if (uri == "" || uri == null
  513. || uri == namespaceBindings.resolve(null))
  514. end = "></"+local+">";
  515. }
  516. }
  517. if (end == null)
  518. end = isEmpty && isHtml ? ">" : useEmptyElementTag == 2 ? " />" : "/>";
  519. writeRaw(end);
  520. inStartTag = false;
  521. }
  522. else
  523. {
  524. if (printIndent >= 0)
  525. {
  526. setIndentation(0, false);
  527. if (prev == ELEMENT_END)
  528. writeBreak(printIndent > 0 ? PrettyWriter.NEWLINE_MANDATORY
  529. : PrettyWriter.NEWLINE_LINEAR);
  530. }
  531. writeRaw("</");
  532. writeQName(type);
  533. writeRaw(">");
  534. }
  535. if (printIndent >= 0)
  536. {
  537. endLogicalBlock("");
  538. }
  539. prev = ELEMENT_END;
  540. if (isHtml && typeName != null && ! escapeText
  541. && ("script".equals(typeName) || "style".equals(typeName)))
  542. escapeText = true;
  543. namespaceBindings = namespaceSaveStack[--elementNesting];
  544. namespaceSaveStack[elementNesting] = null;
  545. elementNameStack[elementNesting] = null;
  546. }
  547. /** Write a attribute for the current element.
  548. * This is only allowed immediately after a startElement. */
  549. public void startAttribute (Object attrType)
  550. {
  551. if (! inStartTag && ! extended)
  552. error("attribute not in element", "SENR0001");
  553. if (inAttribute)
  554. writeRaw('"');
  555. inAttribute = true;
  556. writeRaw(' ');
  557. if (printIndent >= 0)
  558. writeBreakFill();
  559. writeRaw(attrType==null ? "{null name}" : attrType.toString());
  560. writeRaw("=\"");
  561. prev = ' ';
  562. }
  563. public void endAttribute()
  564. {
  565. if (inAttribute)
  566. {
  567. if (prev != KEYWORD)
  568. {
  569. writeRaw('"');
  570. inAttribute = false;
  571. }
  572. prev = ' ';
  573. }
  574. }
  575. public void writeDouble (double d)
  576. {
  577. startWord();
  578. writeRaw(formatDouble(d));
  579. }
  580. public void writeFloat (float f)
  581. {
  582. startWord();
  583. writeRaw(formatFloat(f));
  584. }
  585. /** Helper to format xs:double according to XPath/XQuery specification. */
  586. public static String formatDouble (double d)
  587. {
  588. if (Double.isNaN(d))
  589. return "NaN";
  590. boolean neg = d < 0;
  591. if (Double.isInfinite(d))
  592. return neg ? "-INF" : "INF";
  593. double dabs = neg ? -d : d;
  594. String dstr = Double.toString(d);
  595. // Unfortunately, XQuery's rules for when to use scientific notation
  596. // are different from Java's. So fixup the string, if needed.
  597. if ((dabs >= 1000000 || dabs < 0.000001) && dabs != 0.0)
  598. return RealNum.toStringScientific(dstr);
  599. else
  600. return formatDecimal(RealNum.toStringDecimal(dstr));
  601. }
  602. /** Helper to format xs:float according to XPath/XQuery specification. */
  603. public static String formatFloat (float f)
  604. {
  605. if (Float.isNaN(f))
  606. return "NaN";
  607. boolean neg = f < 0;
  608. if (Float.isInfinite(f))
  609. return neg ? "-INF" : "INF";
  610. float fabs = neg ? -f : f;
  611. String fstr = Float.toString(f);
  612. // Unfortunately, XQuery's rules for when to use scientific notation
  613. // are different from Java's. So fixup the string, if needed.
  614. if ((fabs >= 1000000 || fabs < 0.000001) && fabs != 0.0)
  615. return RealNum.toStringScientific(fstr);
  616. else
  617. return formatDecimal(RealNum.toStringDecimal(fstr));
  618. }
  619. /** Format java.math.BigDecimal as needed for XPath/XQuery's xs:decimal.
  620. * Specifically this means removing trailing fractional zeros, and a trailing
  621. * decimal point. However, note that the XML Schema canonical representation
  622. * does require a decimal point and at least one fractional digit.
  623. */
  624. public static String formatDecimal (BigDecimal dec)
  625. {
  626. /* #ifdef JAVA5 */
  627. return formatDecimal(dec.toPlainString());
  628. /* #else */
  629. // return formatDecimal(dec.toString());
  630. /* #endif */
  631. }
  632. static String formatDecimal (String str)
  633. {
  634. int dot = str.indexOf('.');
  635. if (dot >= 0)
  636. {
  637. int len = str.length();
  638. for (int pos = len; ; )
  639. {
  640. char ch = str.charAt(--pos);
  641. if (ch != '0')
  642. {
  643. if (ch != '.')
  644. pos++;
  645. return pos == len ? str : str.substring(0, pos);
  646. }
  647. }
  648. }
  649. return str;
  650. }
  651. public void print(Object v)
  652. {
  653. if (v instanceof BigDecimal)
  654. v = formatDecimal((BigDecimal) v);
  655. else if (v instanceof Double || v instanceof gnu.math.DFloNum)
  656. v = formatDouble(((Number) v).doubleValue());
  657. else if (v instanceof Float)
  658. v = formatFloat(((Float) v).floatValue());
  659. write(v == null ? "(null)" : v.toString());
  660. }
  661. public void writeObject(Object v)
  662. {
  663. if (v instanceof SeqPosition)
  664. {
  665. clearWordEnd();
  666. SeqPosition pos = (SeqPosition) v;
  667. pos.sequence.consumeNext(pos.ipos, this);
  668. if (pos.sequence instanceof NodeTree)
  669. prev = '-';
  670. return;
  671. }
  672. if (v instanceof Consumable)
  673. {
  674. ((Consumable) v).consume(this);
  675. return;
  676. }
  677. if (v instanceof Keyword)
  678. {
  679. startAttribute(((Keyword) v).getName());
  680. prev = KEYWORD;
  681. return;
  682. }
  683. closeTag();
  684. if (v instanceof UnescapedData)
  685. {
  686. clearWordEnd();
  687. writeRaw(((UnescapedData) v).getData());
  688. prev = '-';
  689. }
  690. else if (v instanceof Char)
  691. Char.print(((Char) v).intValue(), this);
  692. else
  693. {
  694. startWord();
  695. prev = ' ';
  696. print(v);
  697. writeWordEnd();
  698. prev = WORD;
  699. }
  700. }
  701. /** Write each element of a sequence, which can be an array,
  702. * a Sequence or a Consumable. */
  703. //public void writeAll(Object sequence);
  704. /** True if consumer is ignoring rest of element.
  705. * The producer can use this information to skip ahead. */
  706. public boolean ignoring()
  707. {
  708. return false;
  709. }
  710. public void write(String str, int start, int length) {
  711. if (length > 0) {
  712. closeTag();
  713. int limit = start + length;
  714. int count = 0;
  715. while (start < limit) {
  716. char c = str.charAt(start++);
  717. if (mustHexEscape(c)
  718. || (inComment > 0 ? (c == '-' || inComment == 2)
  719. : (c == '<' || c == '>' || c == '&'
  720. || (inAttribute && (c == '"' || c < ' ' ))))) {
  721. if (count > 0)
  722. writeRaw(str, start - 1 - count, count);
  723. write(c);
  724. count = 0;
  725. }
  726. else
  727. count++;
  728. }
  729. if (count > 0)
  730. writeRaw(str, limit - count, count);
  731. }
  732. prev = '-';
  733. }
  734. public void write(char[] buf, int off, int len)
  735. {
  736. if (len > 0)
  737. {
  738. closeTag();
  739. int limit = off + len;
  740. int count = 0;
  741. while (off < limit)
  742. {
  743. char c = buf[off++];
  744. if (mustHexEscape(c)
  745. || (inComment > 0 ? (c == '-' || inComment == 2)
  746. : (c == '<' || c == '>' || c == '&'
  747. || (inAttribute && (c == '"' || c < ' ' )))))
  748. {
  749. if (count > 0)
  750. writeRaw(buf, off - 1 - count, count);
  751. write(c);
  752. count = 0;
  753. }
  754. else
  755. count++;
  756. }
  757. if (count > 0)
  758. writeRaw(buf, limit - count, count);
  759. }
  760. prev = '-';
  761. }
  762. public void writePosition(AbstractSequence seq, int ipos)
  763. {
  764. seq.consumeNext(ipos, this);
  765. }
  766. public void writeBaseUri (Object uri)
  767. {
  768. }
  769. public void beginComment ()
  770. {
  771. closeTag();
  772. if (printIndent >= 0)
  773. {
  774. if (prev == ELEMENT_START || prev == ELEMENT_END || prev == COMMENT)
  775. writeBreak(printIndent > 0 ? PrettyWriter.NEWLINE_MANDATORY
  776. : PrettyWriter.NEWLINE_LINEAR);
  777. }
  778. writeRaw("<!--");
  779. inComment = 1;
  780. }
  781. public void endComment ()
  782. {
  783. writeRaw("-->");
  784. prev = COMMENT;
  785. inComment = 0;
  786. }
  787. public void writeComment(String chars)
  788. {
  789. beginComment();
  790. write(chars);
  791. endComment();
  792. }
  793. public void writeComment(char[] chars, int offset, int length)
  794. {
  795. beginComment();
  796. write(chars, offset, length);
  797. endComment();
  798. }
  799. public void writeCDATA (char[] chars, int offset, int length)
  800. {
  801. if (canonicalizeCDATA)
  802. {
  803. write(chars, offset, length);
  804. return;
  805. }
  806. closeTag();
  807. writeRaw("<![CDATA[");
  808. int limit = offset+length;
  809. // Look for and deal with embedded "]]>". This can't happen with
  810. // data generated from XML, but maybe somebody generated invalid CDATA.
  811. for (int i = offset; i < limit - 2; i++)
  812. {
  813. if (chars[i] == ']' && chars[i+1] == ']' && chars[i+2] == '>')
  814. {
  815. if (i > offset)
  816. writeRaw(chars, offset, i - offset);
  817. writeRaw("]]]><![CDATA[]>");
  818. offset = i + 3;
  819. length = limit - offset;
  820. i = i + 2;
  821. }
  822. }
  823. writeRaw(chars, offset, length);
  824. writeRaw("]]>");
  825. prev = '>';
  826. }
  827. public void writeProcessingInstruction(String target, char[] content,
  828. int offset, int length)
  829. {
  830. if ("xml".equals(target))
  831. needXMLdecl = false;
  832. closeTag();
  833. writeRaw("<?");
  834. writeRaw(target);
  835. writeRaw(' ');
  836. writeRaw(content, offset, length);
  837. writeRaw("?>");
  838. prev = PROC_INST;
  839. }
  840. public void writePosition(SeqPosition position)
  841. {
  842. position.sequence.consumeNext(position.ipos, this);
  843. }
  844. public void error (String msg, String code)
  845. {
  846. throw new RuntimeException("serialization error: "+msg+" ["+code+']');
  847. }
  848. }