2010-06-04 70 views
3

我想在C#中使用正则表达式来匹配xml文档中的一个部分,并在标签中包装该部分。什么是最好的方式来包装一些XML文本标签?

例如,我有本节:

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

,我希望它看起来像这样:

<intro> 
    <bodyText> 
     <p> this is asdf</p> 
     <p> yada yada </p> 
    </bodyText> 
</intro> 

有什么想法?

我正在考虑在C#中使用XPath类,或者只是通过阅读文档和使用正则表达式。我似乎无法想出任何方式。

这里是一个尝试:

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

谢谢!

+5

强制性链接:http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – 2010-06-04 20:55:03

+0

似乎你可能想要XSLT。 – jball 2010-06-04 20:56:27

+0

您使用的是什么版本的.NET? – 2010-06-04 23:53:02

回答

6

我不会为此任务推荐正则表达式。相反,你可以使用LINQ to XML来完成。例如,这里是你如何可以换一个新的标签内的一些标签:

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

结果:

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

我假设你实际的文档从您发布这样的代码需要的例子有很大不同一些适合您的要求的调整,但是如果您阅读XDocument的文档,您应该能够做到您想要的。

+0

虽然我同意这种方法,但我不认为这些代码实际上是做OP所需要的。 – hemp 2010-06-04 21:02:51

+1

@ hemp:是的,我并没有声称他可以盲目地将这些代码复制并粘贴到他的项目中,他的所有问题都将得到解决,但希望这足以启动一个提示。 – 2010-06-04 21:05:21

+0

我再次阅读并自己尝试,我错了 - 你的代码完全按照他的要求。抱歉! – hemp 2010-06-04 23:43:00

1

我会建议使用System.XML和XPath - 我不认为XML被认为是一种类似于HTML的常规语言,当尝试使用正则表达式解析它时会导致问题。

使用类似

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

享受!

相关问题