如何更新XML文件中元素对应的值
现有一个xml文件:
<?xml version="1.0" encoding="utf-16"?>
<componentDocuments>
<componentDocument Version="1.0">
<header>
<flow ID="GOGOGO" nodeID="Begin" >
<fileName>xml/workflows/SignOnFlow.xml </fileName>
<declares />
<sequence outcome="" />
</flow>
<returnStack />
<index>1 </index>
</header>
</componentDocument>
</componentDocuments>
现在想把 <fileName>元素下对应的值xml/workflows/SignOnFlow.xml变为c:\AAA\xml\workflows\SignOnFlow.xml并更新到 <fileName>元素下,即变为新的xml文件:
<?xml version="1.0" encoding="utf-16"?>
<componentDocuments>
<componentDocument Version="1.0">
<header>
<flow ID="GOGOGO" nodeID="Begin" >
<fileName>c:\AAA\xml\workflows\SignOnFlow.xml </fileName>
<declares />
<sequence outcome="" />
</flow>
<returnStack />
<index>1 </index>
</header>
</componentDocument>
</componentDocuments>
请问各位高手该如何去写呢?也请把详细步骤也写出来,在此先谢谢啦!
说明:
此xml文件是程序运行时组装产生的,在计算机上并无对应的文件路径存取,有人说用LINQ可以实现这样的更新,但是本人对LINQ并不是很熟悉,所以要是有会这方面知识的高手请给予讲解,或者用其它方式实现也可,请大家再帮忙解答一下,谢谢!
------解决方案--------------------
var xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
<componentDocuments>
<componentDocument Version=""1.0"">
<header>
<flow ID=""GOGOGO"" nodeID=""Begin"" >
<fileName>xml/workflows/SignOnFlow.xml </fileName>
<declares />
<sequence outcome="""" />
</flow>
<returnStack />
<index>1 </index>
</header>
</componentDocument>
</componentDocuments> ";
var doc = XDocument.Parse(xml);
foreach (var x in doc.Root.Descendants("fileName"))
{
x.Value = x.Value.Replace("xml/workflows/", "c:\\AAA\\xml\\workflows\\");
}
------解决方案--------------------
C# code
XDocument doc = XDocument.Load(Server.MapPath("XMLFile.xml"));
var temp = doc.Element("componentDocuments").Element("componentDocument").Element("header").Element("flow").Element("fileName");
temp.Value = @"c:\AAA\xml\workflows\SignOnFlow.xml";
doc.Save(Server.MapPath("XMLFile.xml"));