/utils/src/org/json/JSONML.java

https://bitbucket.org/crholm/mdfs · Java · 465 lines · 298 code · 45 blank · 122 comment · 120 complexity · d7af33832138a63358357e755a6b46b2 MD5 · raw file

  1. package org.json;
  2. /*
  3. Copyright (c) 2008 JSON.org
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all
  11. copies or substantial portions of the Software.
  12. The Software shall be used for Good, not Evil.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. SOFTWARE.
  20. */
  21. import java.util.Iterator;
  22. /**
  23. * This provides static methods to convert an XML text into a JSONArray or
  24. * JSONObject, and to covert a JSONArray or JSONObject into an XML text using
  25. * the JsonML transform.
  26. * @author JSON.org
  27. * @version 2011-11-24
  28. */
  29. public class JSONML {
  30. /**
  31. * Parse XML values and store them in a JSONArray.
  32. * @param x The XMLTokener containing the source string.
  33. * @param arrayForm true if array form, false if object form.
  34. * @param ja The JSONArray that is containing the current tag or null
  35. * if we are at the outermost level.
  36. * @return A JSONArray if the value is the outermost tag, otherwise null.
  37. * @throws JSONException
  38. */
  39. private static Object parse(
  40. XMLTokener x,
  41. boolean arrayForm,
  42. JSONArray ja
  43. ) throws JSONException {
  44. String attribute;
  45. char c;
  46. String closeTag = null;
  47. int i;
  48. JSONArray newja = null;
  49. JSONObject newjo = null;
  50. Object token;
  51. String tagName = null;
  52. // Test for and skip past these forms:
  53. // <!-- ... -->
  54. // <![ ... ]]>
  55. // <! ... >
  56. // <? ... ?>
  57. while (true) {
  58. if (!x.more()) {
  59. throw x.syntaxError("Bad XML");
  60. }
  61. token = x.nextContent();
  62. if (token == XML.LT) {
  63. token = x.nextToken();
  64. if (token instanceof Character) {
  65. if (token == XML.SLASH) {
  66. // Close tag </
  67. token = x.nextToken();
  68. if (!(token instanceof String)) {
  69. throw new JSONException(
  70. "Expected a closing name instead of '" +
  71. token + "'.");
  72. }
  73. if (x.nextToken() != XML.GT) {
  74. throw x.syntaxError("Misshaped close tag");
  75. }
  76. return token;
  77. } else if (token == XML.BANG) {
  78. // <!
  79. c = x.next();
  80. if (c == '-') {
  81. if (x.next() == '-') {
  82. x.skipPast("-->");
  83. }
  84. x.back();
  85. } else if (c == '[') {
  86. token = x.nextToken();
  87. if (token.equals("CDATA") && x.next() == '[') {
  88. if (ja != null) {
  89. ja.put(x.nextCDATA());
  90. }
  91. } else {
  92. throw x.syntaxError("Expected 'CDATA['");
  93. }
  94. } else {
  95. i = 1;
  96. do {
  97. token = x.nextMeta();
  98. if (token == null) {
  99. throw x.syntaxError("Missing '>' after '<!'.");
  100. } else if (token == XML.LT) {
  101. i += 1;
  102. } else if (token == XML.GT) {
  103. i -= 1;
  104. }
  105. } while (i > 0);
  106. }
  107. } else if (token == XML.QUEST) {
  108. // <?
  109. x.skipPast("?>");
  110. } else {
  111. throw x.syntaxError("Misshaped tag");
  112. }
  113. // Open tag <
  114. } else {
  115. if (!(token instanceof String)) {
  116. throw x.syntaxError("Bad tagName '" + token + "'.");
  117. }
  118. tagName = (String)token;
  119. newja = new JSONArray();
  120. newjo = new JSONObject();
  121. if (arrayForm) {
  122. newja.put(tagName);
  123. if (ja != null) {
  124. ja.put(newja);
  125. }
  126. } else {
  127. newjo.put("tagName", tagName);
  128. if (ja != null) {
  129. ja.put(newjo);
  130. }
  131. }
  132. token = null;
  133. for (;;) {
  134. if (token == null) {
  135. token = x.nextToken();
  136. }
  137. if (token == null) {
  138. throw x.syntaxError("Misshaped tag");
  139. }
  140. if (!(token instanceof String)) {
  141. break;
  142. }
  143. // attribute = value
  144. attribute = (String)token;
  145. if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) {
  146. throw x.syntaxError("Reserved attribute.");
  147. }
  148. token = x.nextToken();
  149. if (token == XML.EQ) {
  150. token = x.nextToken();
  151. if (!(token instanceof String)) {
  152. throw x.syntaxError("Missing value");
  153. }
  154. newjo.accumulate(attribute, XML.stringToValue((String)token));
  155. token = null;
  156. } else {
  157. newjo.accumulate(attribute, "");
  158. }
  159. }
  160. if (arrayForm && newjo.length() > 0) {
  161. newja.put(newjo);
  162. }
  163. // Empty tag <.../>
  164. if (token == XML.SLASH) {
  165. if (x.nextToken() != XML.GT) {
  166. throw x.syntaxError("Misshaped tag");
  167. }
  168. if (ja == null) {
  169. if (arrayForm) {
  170. return newja;
  171. } else {
  172. return newjo;
  173. }
  174. }
  175. // Content, between <...> and </...>
  176. } else {
  177. if (token != XML.GT) {
  178. throw x.syntaxError("Misshaped tag");
  179. }
  180. closeTag = (String)parse(x, arrayForm, newja);
  181. if (closeTag != null) {
  182. if (!closeTag.equals(tagName)) {
  183. throw x.syntaxError("Mismatched '" + tagName +
  184. "' and '" + closeTag + "'");
  185. }
  186. tagName = null;
  187. if (!arrayForm && newja.length() > 0) {
  188. newjo.put("childNodes", newja);
  189. }
  190. if (ja == null) {
  191. if (arrayForm) {
  192. return newja;
  193. } else {
  194. return newjo;
  195. }
  196. }
  197. }
  198. }
  199. }
  200. } else {
  201. if (ja != null) {
  202. ja.put(token instanceof String
  203. ? XML.stringToValue((String)token)
  204. : token);
  205. }
  206. }
  207. }
  208. }
  209. /**
  210. * Convert a well-formed (but not necessarily valid) XML string into a
  211. * JSONArray using the JsonML transform. Each XML tag is represented as
  212. * a JSONArray in which the first element is the tag name. If the tag has
  213. * attributes, then the second element will be JSONObject containing the
  214. * name/value pairs. If the tag contains children, then strings and
  215. * JSONArrays will represent the child tags.
  216. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  217. * @param string The source string.
  218. * @return A JSONArray containing the structured data from the XML string.
  219. * @throws JSONException
  220. */
  221. public static JSONArray toJSONArray(String string) throws JSONException {
  222. return toJSONArray(new XMLTokener(string));
  223. }
  224. /**
  225. * Convert a well-formed (but not necessarily valid) XML string into a
  226. * JSONArray using the JsonML transform. Each XML tag is represented as
  227. * a JSONArray in which the first element is the tag name. If the tag has
  228. * attributes, then the second element will be JSONObject containing the
  229. * name/value pairs. If the tag contains children, then strings and
  230. * JSONArrays will represent the child content and tags.
  231. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  232. * @param x An XMLTokener.
  233. * @return A JSONArray containing the structured data from the XML string.
  234. * @throws JSONException
  235. */
  236. public static JSONArray toJSONArray(XMLTokener x) throws JSONException {
  237. return (JSONArray)parse(x, true, null);
  238. }
  239. /**
  240. * Convert a well-formed (but not necessarily valid) XML string into a
  241. * JSONObject using the JsonML transform. Each XML tag is represented as
  242. * a JSONObject with a "tagName" property. If the tag has attributes, then
  243. * the attributes will be in the JSONObject as properties. If the tag
  244. * contains children, the object will have a "childNodes" property which
  245. * will be an array of strings and JsonML JSONObjects.
  246. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  247. * @param x An XMLTokener of the XML source text.
  248. * @return A JSONObject containing the structured data from the XML string.
  249. * @throws JSONException
  250. */
  251. public static JSONObject toJSONObject(XMLTokener x) throws JSONException {
  252. return (JSONObject)parse(x, false, null);
  253. }
  254. /**
  255. * Convert a well-formed (but not necessarily valid) XML string into a
  256. * JSONObject using the JsonML transform. Each XML tag is represented as
  257. * a JSONObject with a "tagName" property. If the tag has attributes, then
  258. * the attributes will be in the JSONObject as properties. If the tag
  259. * contains children, the object will have a "childNodes" property which
  260. * will be an array of strings and JsonML JSONObjects.
  261. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  262. * @param string The XML source text.
  263. * @return A JSONObject containing the structured data from the XML string.
  264. * @throws JSONException
  265. */
  266. public static JSONObject toJSONObject(String string) throws JSONException {
  267. return toJSONObject(new XMLTokener(string));
  268. }
  269. /**
  270. * Reverse the JSONML transformation, making an XML text from a JSONArray.
  271. * @param ja A JSONArray.
  272. * @return An XML string.
  273. * @throws JSONException
  274. */
  275. public static String toString(JSONArray ja) throws JSONException {
  276. int i;
  277. JSONObject jo;
  278. String key;
  279. Iterator keys;
  280. int length;
  281. Object object;
  282. StringBuffer sb = new StringBuffer();
  283. String tagName;
  284. String value;
  285. // Emit <tagName
  286. tagName = ja.getString(0);
  287. XML.noSpace(tagName);
  288. tagName = XML.escape(tagName);
  289. sb.append('<');
  290. sb.append(tagName);
  291. object = ja.opt(1);
  292. if (object instanceof JSONObject) {
  293. i = 2;
  294. jo = (JSONObject)object;
  295. // Emit the attributes
  296. keys = jo.keys();
  297. while (keys.hasNext()) {
  298. key = keys.next().toString();
  299. XML.noSpace(key);
  300. value = jo.optString(key);
  301. if (value != null) {
  302. sb.append(' ');
  303. sb.append(XML.escape(key));
  304. sb.append('=');
  305. sb.append('"');
  306. sb.append(XML.escape(value));
  307. sb.append('"');
  308. }
  309. }
  310. } else {
  311. i = 1;
  312. }
  313. //Emit content in body
  314. length = ja.length();
  315. if (i >= length) {
  316. sb.append('/');
  317. sb.append('>');
  318. } else {
  319. sb.append('>');
  320. do {
  321. object = ja.get(i);
  322. i += 1;
  323. if (object != null) {
  324. if (object instanceof String) {
  325. sb.append(XML.escape(object.toString()));
  326. } else if (object instanceof JSONObject) {
  327. sb.append(toString((JSONObject)object));
  328. } else if (object instanceof JSONArray) {
  329. sb.append(toString((JSONArray)object));
  330. }
  331. }
  332. } while (i < length);
  333. sb.append('<');
  334. sb.append('/');
  335. sb.append(tagName);
  336. sb.append('>');
  337. }
  338. return sb.toString();
  339. }
  340. /**
  341. * Reverse the JSONML transformation, making an XML text from a JSONObject.
  342. * The JSONObject must contain a "tagName" property. If it has children,
  343. * then it must have a "childNodes" property containing an array of objects.
  344. * The other properties are attributes with string values.
  345. * @param jo A JSONObject.
  346. * @return An XML string.
  347. * @throws JSONException
  348. */
  349. public static String toString(JSONObject jo) throws JSONException {
  350. StringBuffer sb = new StringBuffer();
  351. int i;
  352. JSONArray ja;
  353. String key;
  354. Iterator keys;
  355. int length;
  356. Object object;
  357. String tagName;
  358. String value;
  359. //Emit <tagName
  360. tagName = jo.optString("tagName");
  361. if (tagName == null) {
  362. return XML.escape(jo.toString());
  363. }
  364. XML.noSpace(tagName);
  365. tagName = XML.escape(tagName);
  366. sb.append('<');
  367. sb.append(tagName);
  368. //Emit the attributes
  369. keys = jo.keys();
  370. while (keys.hasNext()) {
  371. key = keys.next().toString();
  372. if (!"tagName".equals(key) && !"childNodes".equals(key)) {
  373. XML.noSpace(key);
  374. value = jo.optString(key);
  375. if (value != null) {
  376. sb.append(' ');
  377. sb.append(XML.escape(key));
  378. sb.append('=');
  379. sb.append('"');
  380. sb.append(XML.escape(value));
  381. sb.append('"');
  382. }
  383. }
  384. }
  385. //Emit content in body
  386. ja = jo.optJSONArray("childNodes");
  387. if (ja == null) {
  388. sb.append('/');
  389. sb.append('>');
  390. } else {
  391. sb.append('>');
  392. length = ja.length();
  393. for (i = 0; i < length; i += 1) {
  394. object = ja.get(i);
  395. if (object != null) {
  396. if (object instanceof String) {
  397. sb.append(XML.escape(object.toString()));
  398. } else if (object instanceof JSONObject) {
  399. sb.append(toString((JSONObject)object));
  400. } else if (object instanceof JSONArray) {
  401. sb.append(toString((JSONArray)object));
  402. } else {
  403. sb.append(object.toString());
  404. }
  405. }
  406. }
  407. sb.append('<');
  408. sb.append('/');
  409. sb.append(tagName);
  410. sb.append('>');
  411. }
  412. return sb.toString();
  413. }
  414. }