开发者

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 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 开发者_Go百科</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:

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>

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.


I would suggest the use of System.XML and XPath - I don't think XML is considered a regular language similar to HTML which causes issues when trying to parse it with Regular expressions.

Use something like

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

Enjoy!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜