XMLHelp(上)
发表于:2007-06-30来源:作者:点击数:
标签:
namespace XmlHelper { using System; using System.Xml; using System.Xml. XP ath; using System.Collections; using System.Net; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Data; /// summary /// This cl
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;
/// <summary>
/// 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.
/// </summary>
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);
/// <summary>
/// Save the XML to a target file.
/// </summary>
public bool SaveToFile(string sTargetFileName)
{
bool bResult = false;
try
{
m_xmlDocument.Save(sTargetFileName);
bResult = true;
}
catch (XmlException e)
{
HandleException ( e );
}
return bResult;
}
/// <summary>
/// Easy way to get the entire Xml string
/// </summary>
public override string ToString()
{
return m_xmlDocument.OuterXml;
}
private void DoPostLoadCreateInit()
{
m_nav = m_xmlDocument.CreateNavigator();
MoveToRoot();
}
/// <summary>
/// Easy way to load XML from a file or URL
/// </summary>
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;
}
/// <summary>
/// Helper method to get string content from a URL - not necessarily XML, but probably
/// </summary>
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;
}
/// <summary>
/// Helper function if navigation is used to ensure we@#re at the root node.
/// </summary>
public bool MoveToRoot()
{
bool bResult = false;
try
{
m_nav.MoveToRoot(); // go to root node!
bResult = true;
}
catch (Exception e)
{
HandleException ( e );
}
return bResult;
}
/// <summary>
/// Gets an ArrayList of XmlNode children using an xPath expression
/// </summary>
public ArrayList GetChildNodesFromCriteria(string xPathExpression)
{
ArrayList al = new ArrayList();
try
{
XmlNodeList nl = m_xmlDocument.SelectNodes(xPathExpression);
if ( nl != null )
{
for ( int i=0; i<nl.Count; i++ )
al.Add (nl.Item(i));
}
}
catch (Exception e)
{
HandleException ( e );
}
return al;
}
/// <summary>
/// Get first child node given an XPath expression
/// </summary>
public XmlNode GetFirstChildNodeFromCriteria (string xPathExpression)
{
XmlNode node = null;
try
{
node = m_xmlDocument.SelectSingleNode(xPathExpression);
}
catch (Exception e)
{
HandleException ( e );
}
return node;
}
/// <summary>
/// Get the Attribute value from a given XmlNode
/// </summary>
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;
}
/// <summary>
/// Get the Attribute int32 (int) value from a given XmlNode
/// </summary>
public int GetAttributeInt32Value(XmlNode node, string sAttributeName)
{
string sVal = GetAttributeValue ( node, sAttributeName);
return sVal != "" ? Convert.ToInt32(sVal) : 0;
}
/// <summary>
/// Get the Attribute floating point/Single value from a given XmlNode
/// </summary>
public float GetAttributeFloatValue(XmlNode node, string sAttributeName)
{
string sVal = GetAttributeValue ( node, sAttributeName);
return sVal != "" ? Convert.ToSingle(sVal) : 0;
}
/// <summary>
/// Get the Attribute double value from a given XmlNode
/// </summary>
public double GetAttributeDoubleValue(XmlNode node, string sAttributeName)
{
string sVal = GetAttributeValue ( node, sAttributeName);
return sVal != "" ? Convert.ToDouble(sVal) : 0.00;
}
/// <summary>
/// Get the Attribute boolean value from a given XmlNode
/// </summary>
public bool GetAttributeBooleanValue(XmlNode node, string sAttributeName)
{
string sVal = GetAttributeValue ( node, sAttributeName);
return sVal != "" ? Convert.ToBoolean(sVal) : false;
}
/// <summary>
/// Get the Element value from a given XmlNode
/// </summary>
public string GetElementValue(XmlNode xmlNode)
{
string sVal = "";
try
{
sVal = Decode(xmlNode.InnerXml);
}
catch (Exception e)
{
HandleException ( e );
}
return sVal;
}
/// <summary>
/// Get the Element Int32 value from a given XmlNode
/// </summary>
public int GetElementInt32Value(XmlNode xmlNode)
{
string sVal = GetElementValue (xmlNode);
return sVal != "" ? Convert.ToInt32(sVal) : 0;
}
/// <summary>
/// Get the Element float/single floating point value from a given XmlNode
/// </summary>
public float GetElementFloatValue(XmlNode xmlNode)
{
string sVal = GetElementValue (xmlNode);
return sVal != "" ? Convert.ToSingle(sVal) : 0;
}
/// <summary>
/// Get the Element Double value from a given XmlNode
/// </summary>
public double GetElementDoubleValue(XmlNode xmlNode)
{
string sVal = GetElementValue (xmlNode);
return sVal != "" ? Convert.ToDouble(sVal) : 0.00;
}
/// <summary>
/// Get the Element Boolean value from a given XmlNode
/// </summary>
public bool GetElementBooleanValue(XmlNode xmlNode)
{
string sVal = GetElementValue (xmlNode);
return sVal != "" ? Convert.ToBoolean(sVal) : false;
}
/// <summary>
/// Get the first Child Element value from a given XmlNode
/// </summary>
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;
}
/// <summary>
/// Get the Child Element int32 value from a given XmlNode and ElementName
/// </summary>
public int GetChildElementInt32Value(XmlNode parentNode, string sElementName)
{
string sVal = GetChildElementValue (parentNode, sElementName);
return sVal != "" ? Convert.ToInt32(sVal) : 0;
}
/// <summary>
/// Get the Child Element floating point/single value from a given XmlNode and ElementName
/// </summary>
public float GetChildElementFloatValue(XmlNode parentNode, string sElementName)
{
string sVal = GetChildElementValue (parentNode, sElementName);
return sVal != "" ? Convert.ToSingle(sVal) : 0;
}
/// <summary>
/// Get the Child Element double value from a given XmlNode and ElementName
/// </summary>
public double GetChildElementDoubleValue(XmlNode parentNode, string sElementName)
{
string sVal = GetChildElementValue (parentNode, sElementName);
return sVal != "" ? Convert.ToDouble(sVal) : 0.00;
}
/// <summary>
/// Get the Child Element boolean value from a given XmlNode and ElementName
/// </summary>
public bool GetChildElementBooleanValue(XmlNode parentNode, string sElementName)
{
string sVal = GetChildElementValue (parentNode, sElementName);
return sVal != "" ? Convert.ToBoolean(sVal) : false;
}
/// <summary>
/// Returns the first XmlNode object matching this element name
/// <seealso cref=@#GetFirstChildXmlNode@#/>
/// </summary>
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;
}
/// <summary>
/// Returns the first XmlNode object matching this element name
/// NOTE: this doesn@#t seem to work if parent is Root! Use GetFirstChildXmlNodeFromRoot
/// <seealso cref=@#GetFirstChildXmlNodeFromRoot@#/>
/// </summary>
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;
}
/// <summary>
/// Returns an XmlNodeList of child nodes matching this element name
/// </summary>
public XmlNodeList GetChildNodesFromRoot(string sElementName)
{
return m_xmlDocument.GetElementsByTagName(sElementName);
}
/// <summary>
/// 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)
/// </summary>
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;
}
原文转自:http://www.ltesting.net