我有一个问题我想在我现有的Xml中添加子元素
请帮我
最佳答案
我正在使用LINQ-to-XML,这对我来说似乎更容易,这就是我的方法
首先加载
/// <summary>
/// loads and returns the XML file with the given name
/// </summary>
/// <param name="modelHesapAdi"> name of the XML file to be returned</param>
/// <returns>returns the xml of given model hesap adı</returns>
public static XElement LoadXMLWithGivenModelHesapAdi(string modelHesapAdi, string xmlDirectory)
{
XElement modelsXmlFile = XElement.Load(xmlDirectory + modelHesapAdi + ".xml");
return modelsXmlFile;
}
在另一个方法中调用上述方法
/// <summary>
/// gets a roommessage nood from CreateRoomMessageXElement
/// and adds it to the related room XML file and saves it
/// </summary>
/// <param name="modelHesapAdi">a string which has the name of the XML file to be changed</param>
/// <param name="incomingMemberHesapAdi">a string to be inserted to the xml file, which has the members name</param>
/// <param name="entranceTime"> a string for time, holds the member's entrance time</param>
public void AddMemberNodeToRoomMembersXMLWithGivenModelHesapAdiAndUyeHesapAdi(string modelHesapAdi,
string incomingMemberHesapAdi,
string entranceTime)
{
XElement modelsXmlFile = BAL.Models.Model.LoadXMLWithGivenModelHesapAdi(modelHesapAdi, xmlDirectory);//loads the xml
XElement roomMember = CreateRoomIncomingMemberXElement(incomingMemberHesapAdi, entranceTime);//creates child element and returns it
modelsXmlFile.Add(roomMember);//adds the child element
modelsXmlFile.Save(xmlDirectory + modelHesapAdi + ".xml");//saves the edited file
}
用于子元素创建
/// <summary>
/// creates and returns roommessage nood
/// </summary>
/// <param name="memberHesapAdi">the sender of the message</param>
/// <param name="message">sent message</param>
/// <param name="timeSent">the time when the message was sent</param>
/// <returns></returns>
private XElement CreateRoomIncomingMemberXElement(string memberHesapAdi, string entranceTime)
{
XElement roomMessage = new XElement("RoomMember",
new XElement("MemberHesapAdi", memberHesapAdi),
new XElement("Time", entranceTime));
return roomMessage;
}
在
CreateRoomIncomingMemberXElement
方法中,您将根据需要创建自己的子元素,然后在AddMemberNodeToRoomMembersXMLWithGivenModelHesapAdiAndUyeHesapAdi
中调用它并将其添加到加载的文件中,然后保存它。