mercredi 29 juillet 2015

Loop through XML nodes and update each nodes with value from database

I have a XML file like this: I'm creating event node for the number of records i have in the database.

<event_list>
<event>
 <servername></servername>
</event>
<event>
<servername></servername>
</event>
<event>
<servername></servername>
</event>
<event>
<title></title>
</event>
</event_list>

I will get value of servers from database. I'm not able to pass each server name to corresponding node. Instead i'm ending up updating all fur nodes with same server name with following function:

public static XmlDocument OpenXmlFile(string fileLocation,     List<ServiceObjects> Sqldata)
{

 eventlist_location = @"C:\Temp\List.xml";

 XMLFileManagement FM = new XMLFileManagement();

FM.CreateXML(eventlist_location);

XmlDocument template = new XmlDocument();

template.Load(fileLocation);

XmlDocument Neweventlist = new XmlDocument();

for (int i = 0; i < Sqldata.Count; i++)

{

 XmlNamespaceManager namespaces = new     XmlNamespaceManager(template.NameTable);

namespaces.AddNamespace("n", "http://www.hp.com/2009");

XmlNode node = template.SelectSingleNode(".//n:event", namespaces);

Neweventlist.Load(eventlist_location);

     Neweventlist.DocumentElement.AppendChild(Neweventlist.ImportNode(template.DocumentElement, true));

 XmlNamespaceManager nsmgr = new XmlNamespaceManager(Neweventlist.NameTable);

namespaces.AddNamespace("abc", "http://ift.tt/1MxC40E");

 foreach (XmlNode Xnode in Neweventlist.SelectNodes(".//*", namespaces))

{

if (Xnode.Name == "servername")

Xnode.InnerText = Sqldata.FirstOrDefault().ServerName.ToString();



}
Neweventlist.Save(eventlist_location);

}

return Neweventlist;

}

Aucun commentaire:

Enregistrer un commentaire