问题描述
朋友,
我有以下格式的XML文件.
< CustomerProfiles>
< UserProfiles>
<详细信息>
<名称> Harish</名称>
</详细信息>
<详细信息>
<名称>雷迪</名称>
</详细信息>
</UserProfiles>
</CustomerProfiles>
现在,我需要在所有Details标签中插入新标签"SurName",如..
.....
<详细信息>
<名称> Harish</名称>
< SurName> Kumar< SurName>
</详细信息>
<详细信息>
<名称>雷迪</名称>
< SurName> Prasad</SurName>
<详细信息>
.....
如何在xml文件中为所有详细信息插入标签.
请任何人帮助我.
谢谢,
Harish
Hi Friends,
I have a XML file in the following format.
<CustomerProfiles>
<UserProfiles>
<Details>
<Name>Harish</Name>
</Details>
<Details>
<Name>Reddy</Name>
</Details>
</UserProfiles>
</CustomerProfiles>
Now, I need to insert the new tag "SurName" inside the all Details tag like..
.....
<Details>
<Name>Harish</Name>
<SurName>Kumar<SurName>
</Details>
<Details>
<Name>Reddy</Name>
<SurName>Prasad</SurName>
<Details>
.....
How to insert the tag for all the details in the xml file.
Plz anyone help me.
Thanks,
Harish
推荐答案
string docPath = @"C:\YourPathHere";
string fileName = "Test.xml";
string fileNameUpdated = "TestUpdated.xml";
// Load xml
XDocument doc = XDocument.Load(Path.Combine(docPath, fileName));
// Select details elements
IEnumerable<xelement> details = doc.Element("CustomerProfiles").Element("UserProfiles").Elements("Details");
// Add SurName tag for every details element
foreach(var detail in details)
{
detail.Add(new XElement("SurName", "SurName value goes here"));
}
// Save it as new file
doc.Save(Path.Combine(docPath, fileNameUpdated));
</xelement>
这篇关于在现有的xml文件中创建新的XML标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!