When you specify
LoadOptions.PreserveWhiteSpace
while loading there will be no whitespace added or removed, so I do not think this is where the problem is.
I think your problem is on saving.
Take a look at the
SaveOptions Enum (System.Xml.Linq) | Microsoft Docs[
^].
It is an optional parameter on
XDocument.Save
.
Specifically you would need the
DisableFormatting
flag to ensure the writer doesn't insert insignificant whitespaces.
But in all cases, you need to learn to debug. Do not try to just look at the input and output and then randomly tweak some code. Single step over the relevant code in the debugger and observe it.
Are the extra newlines present after load? If yes, you need to look into how to load it correctly.
Are they present after removing the bold tags etc? If so, you need to look into the code doing the replacement and try to come up with a solution.
If they are not present in the element when you call save, then it is added by save and you need to look into the flags you pass on to save.
Be careful with the debugger in Visual Studio, it tries to "help" you by rendering new lines as spaces sometimes. Use the "text visualizer" available by clicking the small dropdown menu shown with a magnifying glass next to the value.
Most likely using this flag is the correct approach in your case. But if you are responsible for generating the XML files, and you want to minimize other tools making similar errors processing your files "down the line", you should look into the
xml:space
attribute. It tells any standard compliant XML writer/loaded to preserve the significant whitespaces on both load and save without any additional parameters being needed. Specify it at the root element if you are lazy (and want to make it less likely you forget it somewhere), or to individual elements if you want to keep it "nice" where it can still format as much as possible.