我试图在C#中使用Regex来匹配xml文档中的一个部分并将该部分包装在一个标记内.
例如,我有这个部分:
<intro>
<p>this is the first section of content</p>
<p> this is another</p>
</intro>
Run Code Online (Sandbox Code Playgroud)
我希望它看起来像这样:
<intro>
<bodyText>
<p> this is asdf</p>
<p> yada yada </p>
</bodyText>
</intro>
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
我正在考虑在C#中使用XPath类,或者只是通过阅读文档并使用Regex.我无论如何都无法弄明白.
这是一次尝试:
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();
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
我不建议为此任务使用正则表达式.相反,您可以使用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());
Run Code Online (Sandbox Code Playgroud)
结果:
<intro>
<bodyText>
<p>this is the first section of content</p>
<p> this is another</p>
</bodyText>
</intro>
Run Code Online (Sandbox Code Playgroud)
我假设您的实际文档与您发布的示例有很大不同,因此代码需要进行一些调整以满足您的要求,但如果您阅读XDocument的文档,您应该能够做到您想要的.
| 归档时间: |
|
| 查看次数: |
1013 次 |
| 最近记录: |