1. import org.json.JSONObject;
  2. import org.json.JSONArray;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. class DOMSerializer {
  6. public static String serialize(Object obj) {
  7. if (obj == null) {
  8. return "null";
  9. }
  10. if (obj instanceof String) {
  11. return "\"" + ((String) obj).replace("\\", "\\\\").replace("\"", "\\\""); + "\""; // Escape special chars
  12. }
  13. if (obj instanceof Number) {
  14. return String.valueOf(obj);
  15. }
  16. if (obj instanceof Boolean) {
  17. return String.valueOf((Boolean) obj);
  18. }
  19. if (obj instanceof Map) {
  20. Map<String, Object> map = (Map<String, Object>) obj;
  21. JSONArray jsonArray = new JSONArray();
  22. for (Map.Entry<String, Object> entry : map.entrySet()) {
  23. JSONObject jsonObject = new JSONObject();
  24. jsonObject.put(entry.getKey(), serialize(entry.getValue()));
  25. jsonArray.put(jsonObject);
  26. }
  27. return jsonArray.toString();
  28. }
  29. if (obj instanceof JSONArray) {
  30. JSONArray jsonArray = (JSONArray) obj;
  31. JSONObject jsonObject = new JSONObject();
  32. for (int i = 0; i < jsonArray.length(); i++) {
  33. jsonObject.put(String.valueOf(i), serialize(jsonArray.get(i)));
  34. }
  35. return jsonObject.toString();
  36. }
  37. // Handle DOM element objects directly. Assume they have a 'tagName' and 'attributes'
  38. if (obj instanceof DOMElement) {
  39. DOMElement element = (DOMElement) obj;
  40. JSONObject jsonObject = new JSONObject();
  41. jsonObject.put("tagName", element.tagName);
  42. Map<String, String> attributes = new HashMap<>();
  43. for (String key : element.attributes.keySet()) {
  44. attributes.put(key, element.attributes.get(key));
  45. }
  46. jsonObject.put("attributes", attributes);
  47. return jsonObject.toString();
  48. }
  49. return "null"; // Default case
  50. }
  51. public static void main(String[] args) {
  52. // Example Usage & CLI Interface
  53. if (args.length < 1) {
  54. System.out.println("Usage: java DOMSerializer <DOMElement> [other arguments]");
  55. System.out.println(" (DOMElement should be an instance of the DOMElement class)");
  56. return;
  57. }
  58. Object obj = args[0]; // The DOM element to serialize
  59. String serializedString = serialize(obj);
  60. System.out.println(serializedString);
  61. }
  62. }
  63. class DOMElement {
  64. String tagName;
  65. Map<String, String> attributes;
  66. public DOMElement(String tagName, Map<String, String> attributes) {
  67. this.tagName = tagName;
  68. this.attributes = attributes;
  69. }
  70. }

Add your comment