namespace XmlHelper
{
using System;
using System.Xml;
using System.Xml.XPath;
using System.Collections;
using System.Net;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
///
/// This class attempts to wrap up some common things
/// we need to do when dealing with Xml and C# classes:
/// Load, Save, Add/Remove Attributes/Elements, et al.
///
public class XmlHelper
{
private XmlDocument m_xmlDocument;
private XPathNavigator m_nav;
private string m_sLastErrorMessage;
public enum LoadType { FromString, FromLocalFile, FromURL }
// Constructor
public XmlHelper()
{
m_sLastErrorMessage = "";
m_xmlDocument = new XmlDocument();
}
// Properties...
public string LastErrorMessage
{
get { return m_sLastErrorMessage; }
set { m_sLastErrorMessage = value; }
}
public XmlNode RootNode
{
get { return m_xmlDocument.DocumentElement; }
}
public XmlDocument Document
{
get { return m_xmlDocument; }
}
public XPathNavigator Navigator
{
get { return m_nav; }
}
// delegates - more complex save operations can do it themselves...
public delegate bool Save(string sTargetXML);
///
/// Save the XML to a target file.
///
public bool SaveToFile(string sTargetFileName)
{
bool bResult = false;
try
{
m_xmlDocument.Save(sTargetFileName);
bResult = true;
}
catch (XmlException e)
{
HandleException ( e );
}
return bResult;
}
///
/// Easy way to get the entire Xml string
///
public override string ToString()
{
return m_xmlDocument.OuterXml;
}
private void DoPostLoadCreateInit()
{
m_nav = m_xmlDocument.CreateNavigator();
MoveToRoot();
}
///
/// Easy way to load XML from a file or URL
///
public bool LoadXML(string sourceXMLOrFile, LoadType loadType)
{
bool bLoadResult = false;
try
{
switch (loadType)
{
case XmlHelper.LoadType.FromString:
m_xmlDocument.LoadXml(sourceXMLOrFile); // loading from source XML text
break;
case XmlHelper.LoadType.FromLocalFile:
m_xmlDocument.Load(sourceXMLOrFile); // loading from a file
break;
case XmlHelper.LoadType.FromURL:
{
string sURLContent = GetURLContent(sourceXMLOrFile);
m_xmlDocument.LoadXml(sURLContent);
break;
}
default:
string sErr = "Developer note: No LoadType case supported for " + loadType.ToString();
throw(new Exception(sErr));
}
DoPostLoadCreateInit();
bLoadResult = true;
}
catch (Exception e)
{
HandleException ( e );
}
return bLoadResult;
}
///
/// Helper method to get string content from a URL - not necessarily XML, but probably
///
public string GetURLContent(string sURL)
{
string s = "";
try
{
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(sURL);
HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
StreamReader stream = new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);
s = stream.ReadToEnd();
stream.Close();
}
catch(Exception e)
{
HandleException ( e );
}
return s;
}
///
/// Helper function if navigation is used to ensure we're at the root node.
///
public bool MoveToRoot()
{
bool bResult = false;
try
{
m_nav.MoveToRoot(); // go to root node!
bResult = true;
}
catch (Exception e)
{
HandleException ( e );
}
return bResult;
}
///
/// Gets an ArrayList of XmlNode children using an xPath expression
///
public ArrayList GetChildNodesFromCriteria(string xPathExpression)
{
ArrayList al = new ArrayList();
try
{
XmlNodeList nl = m_xmlDocument.SelectNodes(xPathExpression);
if ( nl != null )
{
for ( int i=0; i al.Add (nl.Item(i)); } } catch (Exception e) { HandleException ( e ); } return al; } /// /// Get first child node given an XPath expression /// public XmlNode GetFirstChildNodeFromCriteria (string xPathExpression) { XmlNode node = null; try { node = m_xmlDocument.SelectSingleNode(xPathExpression); } catch (Exception e) { HandleException ( e ); } return node; } /// /// Get the Attribute value from a given XmlNode /// public string GetAttributeValue(XmlNode node, string sAttributeName) { string sVal = ""; try { XmlAttributeCollection attribColl = node.Attributes; XmlAttribute attrib = attribColl[sAttributeName, ""]; sVal = Decode(attrib.Value); } catch (Exception e) { HandleException ( e ); } return sVal; } /// /// Get the Attribute int32 (int) value from a given XmlNode /// public int GetAttributeInt32Value(XmlNode node, string sAttributeName) { string sVal = GetAttributeValue ( node, sAttributeName); return sVal != "" ? Convert.ToInt32(sVal) : 0; } /// /// Get the Attribute floating point/Single value from a given XmlNode /// public float GetAttributeFloatValue(XmlNode node, string sAttributeName) { string sVal = GetAttributeValue ( node, sAttributeName); return sVal != "" ? Convert.ToSingle(sVal) : 0; } /// /// Get the Attribute double value from a given XmlNode /// public double GetAttributeDoubleValue(XmlNode node, string sAttributeName) { string sVal = GetAttributeValue ( node, sAttributeName); return sVal != "" ? Convert.ToDouble(sVal) : 0.00; } /// /// Get the Attribute boolean value from a given XmlNode /// public bool GetAttributeBooleanValue(XmlNode node, string sAttributeName) { string sVal = GetAttributeValue ( node, sAttributeName); return sVal != "" ? Convert.ToBoolean(sVal) : false; } /// /// Get the Element value from a given XmlNode /// public string GetElementValue(XmlNode xmlNode) { string sVal = ""; try { sVal = Decode(xmlNode.InnerXml); } catch (Exception e) { HandleException ( e ); } return sVal; } /// /// Get the Element Int32 value from a given XmlNode /// public int GetElementInt32Value(XmlNode xmlNode) { string sVal = GetElementValue (xmlNode); return sVal != "" ? Convert.ToInt32(sVal) : 0; } /// /// Get the Element float/single floating point value from a given XmlNode /// public float GetElementFloatValue(XmlNode xmlNode) { string sVal = GetElementValue (xmlNode); return sVal != "" ? Convert.ToSingle(sVal) : 0; } /// /// Get the Element Double value from a given XmlNode /// public double GetElementDoubleValue(XmlNode xmlNode) { string sVal = GetElementValue (xmlNode); return sVal != "" ? Convert.ToDouble(sVal) : 0.00; } /// /// Get the Element Boolean value from a given XmlNode /// public bool GetElementBooleanValue(XmlNode xmlNode) { string sVal = GetElementValue (xmlNode); return sVal != "" ? Convert.ToBoolean(sVal) : false; } /// /// Get the first Child Element value from a given XmlNode /// public string GetChildElementValue(XmlNode parentNode, string sElementName) { string sVal = ""; try { XmlNodeList childNodes = parentNode.ChildNodes; foreach (XmlNode childNode in childNodes) { if (childNode.Name == sElementName) { sVal = GetElementValue ( childNode ); break; } } } catch (Exception e) { HandleException ( e ); } return sVal; } /// /// Get the Child Element int32 value from a given XmlNode and ElementName /// public int GetChildElementInt32Value(XmlNode parentNode, string sElementName) { string sVal = GetChildElementValue (parentNode, sElementName); return sVal != "" ? Convert.ToInt32(sVal) : 0; } /// /// Get the Child Element floating point/single value from a given XmlNode and ElementName /// public float GetChildElementFloatValue(XmlNode parentNode, string sElementName) { string sVal = GetChildElementValue (parentNode, sElementName); return sVal != "" ? Convert.ToSingle(sVal) : 0; } /// /// Get the Child Element double value from a given XmlNode and ElementName /// public double GetChildElementDoubleValue(XmlNode parentNode, string sElementName) { string sVal = GetChildElementValue (parentNode, sElementName); return sVal != "" ? Convert.ToDouble(sVal) : 0.00; } /// /// Get the Child Element boolean value from a given XmlNode and ElementName /// public bool GetChildElementBooleanValue(XmlNode parentNode, string sElementName) { string sVal = GetChildElementValue (parentNode, sElementName); return sVal != "" ? Convert.ToBoolean(sVal) : false; } /// /// Returns the first XmlNode object matching this element name /// /// public XmlNode GetFirstChildXmlNodeFromRoot(string sElementName) { // TODO: isn't there a better/faster/more effiecient way to do this? couldn't find it sifting through documentation! XmlNodeList nodeList = GetChildNodesFromRoot(sElementName); if (nodeList.Count > 0) return nodeList[0]; return null; } /// /// Returns the first XmlNode object matching this element name /// NOTE: this doesn't seem to work if parent is Root! Use GetFirstChildXmlNodeFromRoot /// /// public XmlNode GetFirstChildXmlNode(XmlNode parentNode, string sElementName) { // NOTE: this doesn't seem to work if parent is Root! Use GetFirstChildXmlNodeFromRoot XmlNode foundChildNode = null; try { XmlNodeList childNodes = parentNode.ChildNodes; foreach (XmlNode childNode in childNodes) { if (childNode.Name == sElementName) { foundChildNode = childNode; break; } } } catch (Exception e) { HandleException ( e ); } return foundChildNode; } /// /// Returns an XmlNodeList of child nodes matching this element name /// public XmlNodeList GetChildNodesFromRoot(string sElementName) { return m_xmlDocument.GetElementsByTagName(sElementName); } /// /// Returns an ArrayList (boxed XmlNode objects) of child nodes matching this element name /// This function is recursive in that it will find ALL the children, even if their in /// sub folders (sub child nodes) /// public ArrayList GetRecursiveChildNodesFromParent(XmlNode parentNode, string sElementName) { ArrayList elementList = new ArrayList(); try { XmlNodeList children = parentNode.ChildNodes; foreach (XmlNode child in children) { if (child.Name == sElementName) elementList.Add(child); if (child.HasChildNodes == true) { ArrayList childrenList = GetRecursiveChildNodesFromParent(child, sElementName); if (childrenList.Count > 0) { foreach (XmlNode subChild in childrenList) elementList.Add(subChild); } } } } catch (Exception e) { HandleException ( e ); } return elementList; }

