Link to home
Start Free TrialLog in
Avatar of acadenilla
acadenilla

asked on

Insert using Regex

Given the following string

"<Collections>
<Books>
<book>The Lost Symbol</book>
<book>Dark Tower: Wizard & Glass, The</book>
</Books>
<Cards>
<card>
</card>
</Cards>
</Collections>"

I would like to insert CDATA into each node to get the following result

<Collections>
<Books>
<book>![CDATA[The Lost Symbol]]</book>
<book>![CDATA[Dark Tower: Wizard & Glass, The]]</book>
</Books>
<Cards>
<card>
![CDATA[]]
</card>
</Cards>
</Collections>

Can i do this using regex? Would it be possible to just do nodes with special characters?

If not by regex how else can i achieve this efficiently

language i am using is c#

Thanks

Allan
ASKER CERTIFIED SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of acadenilla
acadenilla

ASKER

thanks jaime that worked.

how about if there was more nodes


"<Collections>
<Books>
<book>The Lost Symbol</book>
<book>Dark Tower: Wizard & Glass, The</book>
</Books>
<Cards>
<card>Mickey Mantle</card>
</Cards>
</Collections>"

<Collections>
<Books>
<book>![CDATA[The Lost Symbol]]</book>
<book>![CDATA[Dark Tower: Wizard & Glass, The]]</book>
</Books>
<Cards>
<card>![CDATA[Mickey Mantle]]
</card>
</Cards>
</Collections>

would i have to create several different regex to achieve this or is there some sort of wild card

maybe "(<\w>(.*?)</w> "?
How many different cases?
Jaime,

There are a few a little over 20.

I could just create some of sort of array of all the node names and loop through it and applying your solution. Just wanted to know if there was some regex that would do this
Yes, you can do that, because having a regex expression with 20 different cases will be a mess.
But for that case I would recommend to load your xml into a XmlDocument class, traverse it and change all the desired tags, but the first option is still valid.
And there were my issue lies. If i try to load the xml string into an XDocument when the xml string has "&" it throws an error


string input = "<Collections><Books><book>The Lost Symbol</book><book>Dark Tower: Wizard & Glass, The</book></Books><Cards><card>Mickey Mant</card></Cards></Collections>";

XDocument doc = XDocument.Parse(input);

Open in new window


hmm maybe it is cause i am using XDocument instead of XmlDocument.
Well, indeed a single & is not good, it should be &amp;
Thanks Jaime, i decided to create an array of all the nodes that i need to do the insert and loop through it and apply the code you have provided