private string updateCredentialInXml(string credentials, SocialConnector connector, string element, string value) { if (string.IsNullOrEmpty(credentials)) credentials = "<socialconnector></socialconnector>"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(credentials); XmlElement elemSc = xmlDoc.FirstChild as XmlElement; //connector.ToString() XmlNodeList nl = elemSc.GetElementsByTagName(connector.ToString()); if (nl.Count == 0) { XmlElement elemCon = xmlDoc.CreateElement(connector.ToString()); XmlElement el = xmlDoc.CreateElement("key"); XmlAttribute attr = xmlDoc.CreateAttribute("name"); attr.Value = element; el.Attributes.Append(attr); attr = xmlDoc.CreateAttribute("value"); attr.Value = value; el.Attributes.Append(attr); elemCon.AppendChild(el); elemSc.AppendChild(elemCon); } else { XmlElement elem = nl[0] as XmlElement; if (elem != null) { XmlNodeList elemList = elem.GetElementsByTagName("key"); bool found = false; foreach (XmlNode node in elemList) { XmlElement el = node as XmlElement; if (el.HasAttributes && el.HasAttribute("name") && el.GetAttribute("name") == element) { found = true; el.SetAttribute("value", value); break; } } if (!found) { XmlElement el1 = xmlDoc.CreateElement("key"); XmlAttribute attr = xmlDoc.CreateAttribute("name"); attr.Value = element; el1.Attributes.Append(attr); attr = xmlDoc.CreateAttribute("value"); attr.Value = value; el1.Attributes.Append(attr); elem.AppendChild(el1); } } } return xmlDoc.OuterXml; }
/* Social connector credentials format example <socialconnector> <credentials id='twitter'> <key name='client_id' value='...'/> <key name='client_secret' value='...'/> <key name='access_token' value='...'/> </credentials> <credentials id='facebook'> <key name='client_id' value='...'/> <key name='client_secret' value='...'/> <key name='access_token' value='...'/> </credentials> <credentials id='soundcloud'> <key name='client_id' value='...'/> <key name='client_secret' value='...'/> <key name='access_token' value='...'/> </credentials> </socialconnector> */ private string getCredentialFromXml(string credentials, SocialConnector connector, string element) { XmlDocument doc = new XmlDocument(); doc.LoadXml(credentials); XmlElement elemSc = doc.FirstChild as XmlElement; if (elemSc != null) { XmlNodeList nl = elemSc.GetElementsByTagName(connector.ToString()); if (nl.Count == 0) return string.Empty; XmlElement elem = nl[0] as XmlElement; // If the element wasn't found we bail out with an empty string if (elem == null) return string.Empty; XmlNodeList elemList = elem.GetElementsByTagName("key"); // if there are no child elements, bail out with an empty string // search through the list for the specified child foreach (XmlNode node in elemList) { XmlElement el = node as XmlElement; if (el != null && (el.HasAttributes && el.HasAttribute("name") && el.GetAttribute("name") == element)) return el.GetAttribute("value"); } } return string.Empty; }