Subhash Sharma

Subhash Sharma
Subhash Sharma

This is Subhash Sharma(Software Engineer) Blog

Welcome to this blog and find every solution.............

Search This Blog

Software Engineer(Subhash Sharma)

Software Engineer(Subhash Sharma)
Software Engineer

Friday, December 10, 2010

Update Existing Xml and If Xml is not created it will create and then update the Existing Xml...

static public void MoveUserInfo(string destFolder)
{
string _sourcePath = "";
string _configurationPath = "";
_sourcePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString(), "UserInfo.xml");
_configurationPath = Path.Combine(Path.Combine(destFolder, "Configuration"), "UserInfo.xml");

if (!Directory.Exists(Path.Combine(destFolder, "Configuration")))
Directory.CreateDirectory(Path.Combine(destFolder, "Configuration"));
if (File.Exists(_configurationPath) == true)
{
updateUserInfoXML(_sourcePath, _configurationPath);
}
else //Create UserInfo.Xml file into Directory if not Exist in the Destination Path..
{
File.Copy(_sourcePath, _configurationPath, true);
}
}

static public void updateUserInfoXML(string pathSource, string pathDestination)
{
try
{
XmlDocument docSource = new XmlDocument();
XmlDocument docDestination = new XmlDocument();
string xmlMmessage = "";
docSource.Load(pathSource);
docDestination.Load(pathDestination);
XmlNodeList elemList = docSource.GetElementsByTagName("Asset");
//XmlNodeList elemListRoll = docSource.GetElementsByTagName("role");
//XmlNodeList elemListUser = docSource.GetElementsByTagName("User");
string attrAssetID;
XmlNodeList eleDestNodeList;
XmlNode eleDestinationNode = docDestination.DocumentElement;

foreach (XmlNode eleSourceNode in elemList)
{
attrAssetID = eleSourceNode.Attributes["assetid"].Value;
// attrRollID = eleSourceNode.Attributes["rollid"].Value;
//attrUserID = eleSourceNode.Attributes["Userid"].Value;

eleDestNodeList = docDestination.SelectNodes("/UserInfo/Asset[@assetid='" + attrAssetID.ToString() + "']");

if (eleDestNodeList.Count > 0)
{
eleDestinationNode = docDestination.SelectSingleNode("/UserInfo/Asset[@assetid='" + attrAssetID.ToString() + "']");
//docSource.AppendChild()
//---IF NODE EXISTS THEN REPLACE THE SOURCE NODE WITH TARGET NODE
XmlDocumentFragment fragment = docDestination.CreateDocumentFragment();
fragment.InnerXml = eleSourceNode.OuterXml;
eleDestinationNode.ParentNode.ReplaceChild(fragment, eleDestinationNode);
xmlMmessage = "Sucessfully replaced";
}
else
{
//---IF NODE IS NOT EXISTS THEN APPEND THE SOURCE NODE WITH TARGET NODE

XmlDocumentFragment fragment = docDestination.CreateDocumentFragment();
fragment.InnerXml = eleSourceNode.OuterXml;
eleDestinationNode.AppendChild(fragment);
xmlMmessage = "Sucessfully Append";
}
}
docDestination.PreserveWhitespace = true;
docDestination.Save(pathDestination);
Console.WriteLine(xmlMmessage);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
Console.ReadLine();
}
}

No comments:

Post a Comment