如何将HtmlAgilityPack.HtmlNode[]转换为byte[]?附代码场景
Got it, let's break this down. You've already grabbed those <span> nodes into a HtmlNode[] using HtmlAgilityPack, and now you need to turn that array into a byte[] to stash in a dictionary. Here are two straightforward approaches depending on your needs:
Option 1: Serialize via Combined HTML String
This is the simplest route—just convert each node's HTML content into a string, combine them, then turn that string into bytes.
using System.Linq; using System.Text; // Convert each HtmlNode to its full HTML markup string combinedSpanHtml = string.Join(Environment.NewLine, nodes.Select(node => node.OuterHtml)); // Convert the combined string to a byte array (use UTF8 or your preferred encoding) byte[] spanBytes = Encoding.UTF8.GetBytes(combinedSpanHtml);
Why this works:
Each HtmlNode has an OuterHtml property that gives you the full HTML of the node (including the <span> tag itself and all its content). Joining them into a single string makes it easy to convert to bytes, and when you need to get the nodes back later, you can just convert the byte array back to a string and load it into a new HtmlDocument.
Option 2: Structured Serialization with JSON
If you need to preserve more of the HtmlNode's internal structure (like attributes, child node relationships, etc.) instead of just the raw HTML, use JSON serialization. We'll use Newtonsoft.Json (Json.NET) here—just install it via NuGet if you haven't already.
using Newtonsoft.Json; using System.Text; // Serialize the HtmlNode array to a JSON string, handling circular references string nodesJson = JsonConvert.SerializeObject(nodes, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented // Optional: makes the JSON easier to read }); // Convert the JSON string to a byte array byte[] spanBytes = Encoding.UTF8.GetBytes(nodesJson);
Note:
HtmlAgilityPack's HtmlNode has some circular references (like nodes referencing their parent), so we set ReferenceLoopHandling.Ignore to avoid serialization errors. When you want to retrieve the nodes later, just deserialize the byte array back to a HtmlNode[] using JsonConvert.DeserializeObject<HtmlNode[]>().
Storing in the Dictionary
Once you have your byte[], adding it to a dictionary is straightforward:
Dictionary<string, byte[]> myDictionary = new Dictionary<string, byte[]>(); myDictionary["emailSpanNodes"] = spanBytes;
Just remember to reverse the process when you need to access the nodes again—convert the byte array back to a string, then either parse the HTML or deserialize the JSON to get your HtmlNode[] back.
内容的提问来源于stack exchange,提问作者RookieCoder

