Recursive AI

Save and replay HTML edits as JSON in C#

onehtml is a free, open-source HTML library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Save HTML changes as JSON, then replay them against a freshly parsed copy of the page.

Terminal
dotnet add package RecursiveAI.OneHtml

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneHtml;
using RecursiveAI.OneHtml.Editing;
 
string html =
    "<p id='notice'>Payment due</p>";
var document = Document.Parse(html);
var notice = document.Root
    .QuerySelector("#notice");
var edits = EditJson.Create(document,
    [Edit.SetAttribute(
        notice, "title", "Invoice")]);
File.WriteAllText(
    "edits.json", edits.ToJson());
var saved = EditJson.Parse(
    File.ReadAllText("edits.json"));
var replay = saved.Replay(Document.Parse(html));
foreach (var outcome in replay.Outcomes)
    Console.WriteLine(outcome.Status);
if (replay.Succeeded)
    Console.WriteLine(
        replay.Batch!.Document!.Source.Text);

Prints Applied and <p id='notice' title='Invoice'>Payment due</p>.

Unzip the example, then dotnet run.

The full program

The input HTML is inline. The program saves edits.json, reparses the original markup, replays the edit, then tries a page without the target. An unresolved target is reported as Stale; the transaction applies nothing.

C#
using RecursiveAI.OneHtml;
using RecursiveAI.OneHtml.Editing;
 
string html = "<p id='notice'>Payment due</p>";
var document = Document.Parse(html);
var edits = EditJson.Create(document,
    [Edit.SetAttribute(document.Root.QuerySelector("#notice"), "title", "Invoice")]);
File.WriteAllText("edits.json", edits.ToJson());
var saved = EditJson.Parse(File.ReadAllText("edits.json"));
var replay = saved.Replay(Document.Parse(html));
foreach (var outcome in replay.Outcomes)
    Console.WriteLine(outcome.Status);
if (replay.Succeeded)
    Console.WriteLine(replay.Batch!.Document!.Source.Text);
var missing = saved.Replay(Document.Parse("<p>Different page</p>"));
Console.WriteLine($"Missing target: {missing.Outcomes[0].Status}");
Console.WriteLine($"Applied: {missing.Succeeded}");
Text
Applied
<p id='notice' title='Invoice'>Payment due</p>
Missing target: Stale
Applied: False

The generated edits.json contains:

JSON
{"format":"onehtml-edits","version":1,"edits":[{"op":"setAttribute","target":{"locator":"#notice","fingerprint":{"tag":"p","attrs":{"id":"notice"},"text":"sha256:a648708bed4aa73305e0494b903c63f6be3788c453452e2e26cc03575564eada","path":"sha256:d93ba5dc97cf0414d2c0f8a81c1e58687ea26aa546e106e130727410521fe024"},"anchor":{"start":0,"end":30,"bytes":"sha256:ba11c4b987765e47762833e946d0f3f0e5753cb3db29470343692bf88e8bf5ef"}},"name":"title","value":"Invoice"}]}

Variations

Replace the save line to write indented JSON. Parsing and replay produce the same output.

C#
File.WriteAllText("edits.json", edits.ToJson(indented: true));

Lossless HTML editing · CSS selectors

The short answer

Create an edit envelope—the JSON container for the format version, edits and their saved targets—with EditJson.Create, write it with ToJson, and read it with EditJson.Parse. Call Replay on a freshly parsed document. Check Succeeded before reading the updated document from Batch.Document, and inspect every outcome when replay does not succeed.

The saved JSON describes changes, not a serialized document object. In the example, the change adds a title attribute to the paragraph identified by notice. The second copy starts with the original markup, not with the already edited result.

How do I serialize HTML edits as JSON in C#?

Use the edit-format API rather than serializing live DOM node handles. An in-memory edit targets a node in one document snapshot; the JSON form needs enough durable information to find that node in a later copy. EditJson.Create builds that saved representation from the original document and edits.

The versioned edit format has a format value of onehtml-edits and version 1. It records an operation, target and the operation’s arguments. Targets may contain a locator, fingerprint and byte anchor: a selector identifying the element, a summary of its identifying properties, and a saved source range with a hash of its bytes. That information is why the file can be replayed instead of merely deserialized into a list of strings.

The file is compact by default. The variation uses indented: true to make it easier to review; it does not change the meaning of the edit. Keep the envelope intact when storing it in a database or sending it to another process. A format or version the reader does not support is rejected rather than silently reinterpreted.

How do I replay saved HTML edits in C#?

Parse the saved envelope, parse the destination markup, then call Replay. The example deliberately creates a new Document for replay. It prints each outcome and reads the new source only after success. That avoids mistaking an unapplied change for an updated page.

Replay resolves targets against the destination as it currently exists. It first considers an exact byte anchor, then a locator when necessary, and checks the fingerprint according to the format’s resolution rules. A locator alone is not permission to edit whichever similar-looking paragraph happens to be present.

A saved document URL or document hash is informative; replay does not use it as an automatic approval check. Applications that require an exact source revision should enforce that requirement themselves before replay. The saved target information instead lets replay determine whether the intended node can still be identified.

What happens when an HTML edit target is missing?

The full program’s second replay uses <p>Different page</p>. It reports Stale and Succeeded is false. No change is applied. A transaction with any non-applied outcome applies nothing, including edits whose targets could otherwise be resolved.

Other outcomes distinguish ambiguous targets, invalid operations, lossless-write failures and edits not attempted because another edit did not resolve. Log those outcomes rather than blindly retrying with a broader selector. If the source page changed, review it and create a new edit against the intended target.

The format cannot distinguish two byte-identical element copies in every situation. Its documented anchor rules can accept matching bytes at the saved position, while a locator that matches multiple copies can be ambiguous when that anchor no longer holds. Durable targets reduce accidental changes; they are not a replacement for reviewing a substantially changed source.

All onehtml recipes