-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHtmlParser.cs
More file actions
358 lines (307 loc) · 14 KB
/
HtmlParser.cs
File metadata and controls
358 lines (307 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace HtmlParserLibrary
{
public class HtmlParser
{
private int idCounter = 1; // Initialize a counter for generating unique IDs
public string ConvertHtmlToJson(string htmlContent)
{
try
{
// HTML içeriğini önceden işliyoruz
string preprocessedHtml = PreprocessHtmlForXml(htmlContent);
// HTML içeriğini tek bir kök element içine sarıyoruz
string wrappedHtmlContent = $"<root>{preprocessedHtml}</root>";
// XDocument ile parse ediyoruz
var document = XDocument.Parse(wrappedHtmlContent);
var rootElement = ConvertNodeToJson(document.Root);
JsonSerializerOptions jso = new JsonSerializerOptions();
jso.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
jso.WriteIndented = true;
return JsonSerializer.Serialize(rootElement, jso);
}
catch (Exception ex)
{
// XML parse hatası durumunda hatalı içeriği ham haliyle geri döndür
return JsonSerializer.Serialize(new
{
type = "rawHtml",
isEditable = false,
content = htmlContent
});
}
}
private string PreprocessHtmlForXml(string htmlContent)
{ // Self-closing tagleri uygun formatta değiştir
htmlContent = Regex.Replace(htmlContent, @"<(\w+)([^>]*)/>", "<$1$2></$1>");
// '&' karakterini XML uyumlu hale getiriyoruz
htmlContent = htmlContent.Replace("&", "&");
return htmlContent;
}
private dynamic ConvertNodeToJson(XElement element)
{
// Check if the element is editable
var isEditable = IsEditableElement(element);
// Create a list to store content
var contentList = new List<dynamic>();
// Iterate through all child nodes
foreach (var node in element.Nodes())
{
if (node is XElement childElement)
{
// If it's an element, recursively process it
contentList.Add(ConvertNodeToJson(childElement));
}
else if (node is XText textNode)
{
// If it's text, create a new JSON element for the text with an ID
contentList.Add(new
{
id = (idCounter++).ToString("D5"),
type = "text",
isEditable = true, // Text nodes are editable
content = textNode.Value
});
}
}
// Create the JSON structure
var jsonElement = new
{
id = (idCounter++).ToString("D5"),
type = element.Name.LocalName,
attributes = element.Attributes().ToDictionary(attr => attr.Name.LocalName, attr => attr.Value),
isEditable = isEditable,
content = contentList
};
return jsonElement;
}
private bool IsEditableElement(XElement element)
{
string[] nonEditableTags = { "img", "video", "meta", "script", "style", "br", "hr" };
if (nonEditableTags.Contains(element.Name.LocalName.ToLower()))
{
return false;
}
bool hasChildElements = element.Elements().Any();
if (hasChildElements)
{
return false;
}
return !string.IsNullOrWhiteSpace(element.Value);
}
public string ConvertJsonToHtml(string jsonContent)
{
var jsonObject = JsonSerializer.Deserialize<JsonElement>(jsonContent);
// Eğer JSON içeriği bir "root" elemanı içeriyorsa, sadece içeriğini işleyelim
if (jsonObject.ValueKind == JsonValueKind.Object &&
jsonObject.TryGetProperty("type", out JsonElement typeElement) &&
typeElement.GetString() == "root")
{
if (jsonObject.TryGetProperty("content", out JsonElement contentElement))
{
var htmlBuilder = new StringBuilder();
// Sadece root'un içeriğini HTML'ye dönüştürüyoruz
foreach (JsonElement child in contentElement.EnumerateArray())
{
ConvertJsonToHtmlRecursive(child, htmlBuilder);
}
return Regex.Unescape(htmlBuilder.ToString());
}
}
// Eğer root elemanı yoksa normal şekilde işleme devam
return ConvertJsonToHtmlRecursive(jsonObject, new StringBuilder());
}
public string ConvertJsonToHtmlRecursive(JsonElement jsonObject, StringBuilder htmlBuilder)
{
if (jsonObject.ValueKind == JsonValueKind.Object)
{
if (jsonObject.TryGetProperty("type", out JsonElement typeElement))
{
string tagName = typeElement.GetString();
// Eğer etiket tipi "text" ise, sadece içeriği yazdır, etiketin kendisini değil.
if (tagName == "text")
{
if (jsonObject.TryGetProperty("content", out JsonElement textContentElement))
{
htmlBuilder.Append(textContentElement.GetString());
}
}
else
{
htmlBuilder.Append($"<{tagName}");
if (jsonObject.TryGetProperty("attributes", out JsonElement attributesElement))
{
foreach (JsonProperty attribute in attributesElement.EnumerateObject())
{
htmlBuilder.Append($" {attribute.Name}=\"{attribute.Value.GetString()}\"");
}
}
htmlBuilder.Append(">");
if (jsonObject.TryGetProperty("content", out JsonElement contentElement))
{
if (contentElement.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement child in contentElement.EnumerateArray())
{
ConvertJsonToHtmlRecursive(child, htmlBuilder);
}
}
else if (contentElement.ValueKind == JsonValueKind.String)
{
htmlBuilder.Append(contentElement.GetString());
}
}
htmlBuilder.Append($"</{tagName}>");
}
}
}
else if (jsonObject.ValueKind == JsonValueKind.String)
{
htmlBuilder.Append(jsonObject.GetString());
}
return htmlBuilder.ToString();
}
public List<string> ProcessJsonData(string jsonContent)
{
var jsonObject = JsonSerializer.Deserialize<JsonElement>(jsonContent);
var processedList = new List<string>();
var currentChunk = new StringBuilder();
int chunkCounter = 1;
int chunkIndex = 100;
ProcessJsonRecursive(jsonObject, currentChunk, processedList, ref chunkCounter, ref chunkIndex);
if (currentChunk.Length > 0)
{
processedList.Add($"##{chunkIndex:000}##{currentChunk}");
}
return processedList;
}
private void ProcessJsonRecursive(JsonElement jsonObject, StringBuilder currentChunk, List<string> processedList, ref int chunkCounter, ref int chunkIndex)
{
if (jsonObject.ValueKind == JsonValueKind.String || jsonObject.ValueKind == JsonValueKind.Number)
{
currentChunk.Append(jsonObject.ToString());
if (currentChunk.Length >= 4000)
{
processedList.Add($"##{chunkIndex:000}##{currentChunk.ToString()}");
currentChunk.Clear();
chunkIndex++;
}
}
else if (jsonObject.ValueKind == JsonValueKind.Array)
{
foreach (var item in jsonObject.EnumerateArray())
{
ProcessJsonRecursive(item, currentChunk, processedList, ref chunkCounter, ref chunkIndex);
}
}
else if (jsonObject.ValueKind == JsonValueKind.Object)
{
bool hasEditableContent = false;
if (jsonObject.TryGetProperty("isEditable", out JsonElement isEditableElement) && isEditableElement.GetBoolean())
{
hasEditableContent = true;
if (jsonObject.TryGetProperty("id", out JsonElement idElement))
{
currentChunk.Append($"##{idElement.GetString()}##");
}
}
if (jsonObject.TryGetProperty("content", out JsonElement contentElement))
{
if (contentElement.ValueKind == JsonValueKind.Array)
{
foreach (var child in contentElement.EnumerateArray())
{
ProcessJsonRecursive(child, currentChunk, processedList, ref chunkCounter, ref chunkIndex);
}
}
else if (contentElement.ValueKind == JsonValueKind.String || contentElement.ValueKind == JsonValueKind.Number)
{
if (hasEditableContent)
{
currentChunk.Append(contentElement.ToString());
if (currentChunk.Length >= 4000)
{
processedList.Add($"##{chunkIndex:000}##{currentChunk}");
currentChunk.Clear();
chunkIndex++;
}
}
}
}
}
}
public Dictionary<string, string> ParseEditedContent(string editedContent)
{
var finalEditedContent = editedContent.Replace("# #", "##");
var chunks = new Dictionary<string, string>();
string pattern = @"##\s*(?<id>\d{5})\s*##\s*(?<content>.*?)(?=(\s*##|\s*$))"; // ID'leri ve içerikleri yakalamak için güncellenmiş regex
// Tüm ID'leri ve içerikleri yakala
var matches = Regex.Matches(finalEditedContent, pattern);
foreach (Match match in matches)
{
string id = match.Groups["id"].Value;
string content = match.Groups["content"].Value;
chunks[id] = content;
}
return chunks;
}
private JsonObject CloneJsonObject(JsonObject original)
{
var jsonString = original.ToJsonString();
return JsonNode.Parse(jsonString).AsObject();
}
public JsonObject UpdateJsonRecursive(JsonObject jsonObject, Dictionary<string, string> editedChunks, bool isRoot = false)
{
if (jsonObject.TryGetPropertyValue("id", out JsonNode idNode))
{
string id = idNode.ToString();
// Eğer ID editedChunks içinde varsa ve içerik boş değilse, content'i güncelle
if (editedChunks.ContainsKey(id) && !isRoot)
{
var newContent = editedChunks[id];
if (!string.IsNullOrEmpty(newContent))
{
jsonObject["content"] = JsonValue.Create(newContent);
}
}
}
// İçerik bir array ise, recursive olarak alt öğelere in
if (jsonObject.TryGetPropertyValue("content", out JsonNode contentNode))
{
if (contentNode is JsonArray contentArray)
{
for (int i = 0; i < contentArray.Count; i++)
{
if (contentArray[i] is JsonObject nestedObject)
{
// Burada nesne manuel olarak kopyalanıyor
var clonedNestedObject = CloneJsonObject(nestedObject);
contentArray[i] = UpdateJsonRecursive(clonedNestedObject, editedChunks);
}
}
}
else if (contentNode is JsonObject nestedObject)
{
// Eğer content bir object ise, recursive olarak güncelle
jsonObject["content"] = UpdateJsonRecursive(CloneJsonObject(nestedObject), editedChunks);
}
}
return jsonObject;
}
public string UpdateJsonWithEditedContent(string jsonContent, Dictionary<string, string> editedChunks)
{
var jsonObject = JsonSerializer.Deserialize<JsonObject>(jsonContent);
var updatedJson = UpdateJsonRecursive(jsonObject, editedChunks, true);
JsonSerializerOptions jso = new JsonSerializerOptions();
jso.Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
jso.WriteIndented = true;
return JsonSerializer.Serialize(updatedJson, jso);
}
}
}