What is the best way to wrap some text in an xml tag?

I am trying to use Regex in C # to match a section in an XML document and wrap this section inside 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 thought about this using the XPath class in C # or just reading the document and using Regex. I just can't figure it out anyway.

here is 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();
    }

Thank!

+3
source share
2 answers

I would not recommend regular expressions for this task. Instead, you can do this with LINQ to XML. For example, here is how you can wrap some tags inside a new tag:

XDocument doc = XDocument.Load("input.xml");
var section = doc.Root.Elements("p");
doc.Root.ReplaceAll(new XElement("bodyText", section));
Console.WriteLine(doc.ToString()); 

Result:

<intro>
  <bodyText>
    <p>this is the first section of content</p>
    <p> this is another</p>
  </bodyText>
</intro>

, , , XDocument, , .

+6

System.XML XPath - , XML , HTML, .

-

XMLDocument doc = new XMLDocument();
doc.Load("Path to your xml document");

!

+1

Source: https://habr.com/ru/post/1748596/


All Articles