I am working with some XML-like text that comes from a vendor. The text looks likes this:

Notice that there is a carriage return/line feed after each element's closing tag. We have a program that creates a new XML-like document, to send back to the vendor. It's basically just a text file. The problem is, though, our resulting document does not contain a carriage-return/line-feed after each closing tag.
We can't modify the program, but I figured we could write a small program that would read the text document in, add a CR/LF to the end of each closing tag, then write it back out, basically just modifying the text to look like the vendor's document.
My first attempt at doing this didn't work well. Here's the code I used:
// Add CR/LF to file.
var myFile = File.ReadAllText(_filePath);
myFile = myFile.Replace(">", ">" + Environment.NewLine);
File.WriteAllText(_filePath, myFile);
However, I forgot that doing the replace on the > character, will also do it for the starting element tag, too. So, I now have a CR/LF after the start and end tags:

So, basically, I'm wondering how I can just add the CR/LF after the ending closing tag?
I should also mention that the file that I'm trying to do this to is one long string of xml-like text. So, it looks like this:
<name>nextOver.gif</name><relativelink>images/nextOver.gif</relativelink><resourceflags>0</resourceflags>...
I just want to read the text file in, add a CR/LF after each closking tag, then write out the modified file.
EDIT: I just had a thought. Perhaps I can use RegEx to pick out each closing tag, based on whether the tag contains a / character then, somehow, add the CR/LF after...
You can use Regex :
string result = Regex.Replace(str, "</([^>]*)>", "</$1>" + Environment.NewLine);
If the text is a valid XML, try to read it to the XmlDocument and then write it back with the following XmlWriterSettings:
using (XmlWriter writer = XmlWriter.Create(filename, new XmlWriterSettings
{ Indent = true, IndentChars = String.Empty }))
{
xmlDocument.Save(writer);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With