Reputation: 497
I have a few strings and I would like to insert some line breaks into them at certain points.
I figured out a few of the logistics but as a whole I can't seem to crack this problem, probably because I have limited experience with regex.
Basically I have a long string of XML tags that is all on one line. I want to add line breaks at certain points to get the data more formatted and looking nice. I am using CodeMirror to display this data on a webpage but for some reason its all on line #1.
So I need to go from something like this:
<Sample><Name></Name><PhoneNumber><AreaCode></AreaCode><Number></Number></PhoneNumber></Sample>
To something like this:
<Sample>
<Name></Name>
<PhoneNumber>
<AreaCode></AreaCode>
<Number></Number>
</PhoneNumber>
</Sample>
CodeMirror will take care of the rest of the formatting all I need to do is insert the line breaks in the right spot using regex or a loop of some sort. The Tags will or can change so I am guessing regex has to be used.
I have had success inserting line breaks with \n and 
 but can't seem to get regex to detect the proper locations.
Any help would be greatly appreciated. Thanks.
UPDATE I overlooked this but the brackets are in fact being sent as < and >
So example tag would look like:
<PhoneNumber>
or
</PhoneNumber>
So basically need to insert a \n
after every >
that is a closing tag or a beginning tag that contains children tags.
Upvotes: 0
Views: 1050
Reputation: 63708
Try this regex
pattern:
>\s*<(?!/)
Replacement string : >\n<
>\s*<(?!/)
Upvotes: 0
Reputation: 12375
There be dragons here.
I'd like to point you to a very similar question answered awhile ago that does a good job of explaining why you should NOT try to parse XML yourself unless you REALLY know what you're doing.
Use an XML deserializer if you want to get nice line breaks and that sort of thing.
Upvotes: 1