需求:需要将文件中的“旧格式”内容转换成“新”的内容
旧格式:
<root>
<name>张三</name>
<year>76</year>
<character>
<good>20%</good>
</character>
<hight>176</hight>
</root>
新格式:
<root>
<name>张三</name>
<year>76</year>
<character>45</character>
<hight>176</hight>
</root>
实现代码如下:
// filePath = "D:\Test.tmp" 或者filePath = "D:\Test.xml"
// content = "45"
private bool ReBuildXml(string filePath, string content )
{
try
{
// 1.解析文件
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
// 2.输出xml字符串
string newXmlContent = doc.OuterXml;
// 3.编辑字符串:使用正则表达实现替换两个字符串之间的内容
Regex r = new Regex("(?<=(<character>))[.\\s\\S]*?(?=(</character>))");
newXmlContent = r.Replace(newXmlContent, content , 1);
// 4.重新保存文件
doc.LoadXml(newXmlContent);
doc.Save(filePath);
}
catch (Exception ex)
{
TestLog.LogError(ex.Message);
return false;
}
return true;
}