XPDXMLElement.m 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // XPDXMLElement.m
  3. // XMLParseDome
  4. //
  5. // Copyright © 2014-2023 PDF Technologies, Inc. All Rights Reserved.
  6. //
  7. // THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW
  8. // AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE ComPDFKit LICENSE AGREEMENT.
  9. // UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES.
  10. // This notice may not be removed from this file.
  11. //
  12. #import "XPDXMLElement.h"
  13. @implementation XPDXMLElement
  14. - (instancetype)init
  15. {
  16. self = [super init];
  17. if (self) {
  18. _text=[[NSMutableString alloc]init];
  19. }
  20. return self;
  21. }
  22. -(NSMutableArray<XPDXMLElement *> *)childElement{
  23. if (!_childElement) {
  24. _childElement = [[NSMutableArray alloc]init];
  25. }
  26. return _childElement;
  27. }
  28. -(NSString *)description{
  29. NSDictionary *dic = [self convertToDic];
  30. if ([NSJSONSerialization isValidJSONObject:dic]) {
  31. NSError *error;
  32. NSData *jsonData=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
  33. if (error) {
  34. return @"{}";
  35. }
  36. if (jsonData) {
  37. @try {
  38. NSString *jsonStr = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
  39. return jsonStr;
  40. } @catch (NSException *exception) {
  41. }
  42. }
  43. }
  44. return @"{}";
  45. }
  46. -(NSDictionary *)convertToDic{
  47. NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
  48. if (self.name) {
  49. dic[self.name]=self.text;
  50. }
  51. if (self.attribute&&self.attribute.count>0) {
  52. [dic addEntriesFromDictionary:self.attribute];
  53. }
  54. if (self.childElement&&self.childElement.count>0) {
  55. NSMutableArray *child=[[NSMutableArray alloc]init];
  56. for (XPDXMLElement *element in self.childElement) {
  57. NSDictionary *childDic = [element convertToDic];
  58. if (element.childElement&&element.childElement.count>0) {
  59. [child addObject:childDic];
  60. }else{
  61. [dic addEntriesFromDictionary:childDic];
  62. }
  63. }
  64. if (child.count>0) {
  65. dic[@"child"]=child;
  66. }
  67. }
  68. return dic;
  69. }
  70. @end