I am trying to use Regex in C# to match a section in an xml document and wrap that section inside of a tag.
For example, I have this section:
<intro>
<p>this is the first section of content</p>
<p> this is another</p>
</intro>
and I want it to look like this:
<intro>
<bodyText>
<p> this is asdf</p>
<p> yada yada </p>
</bodyText>
</intro>
any thoughts?
I was considering doing it using the XPath class in C# or just by reading in the document and using Regex. I just can’t seem to figure it out either way.
here is the one try:
StreamReader reader = new StreamReader(filePath);
string content = reader.ReadToEnd();
reader.Close();
/* The regex stuff would go here */
StreamWriter writer = new StreamWriter(filePath);
writer.Write(content);
writer.Close();
}
Thanks!
I wouldn’t recommend regular expressions for this task. Instead you can do it using LINQ to XML. For example, here is how you could wrap some tags inside a new tag:
Result:
I assume that your actual document differs considerably from the example you posted so the code will need some adjustment to fit your requirements, but if you read the documentation for XDocument you should be able to do what you want.