Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a carriage return after XML ending closing tag?

Tags:

c#

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

Vendor Supplied Document

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:

enter image description here

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...

like image 310
Kevin Avatar asked Dec 29 '25 19:12

Kevin


2 Answers

You can use Regex :

string result = Regex.Replace(str, "</([^>]*)>", "</$1>" + Environment.NewLine);
like image 200
brz Avatar answered Dec 31 '25 09:12

brz


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);
}
like image 43
Dmitry Avatar answered Dec 31 '25 08:12

Dmitry