繁体中文
设为首页
加入收藏
当前位置:.Net技术首页 >> Asp.Net开发 >> XMLHelp(上)

XMLHelp(上)

2007-07-15 08:00:00  作者:  来源:互联网  浏览次数:0  文字大小:【】【】【
简介: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; ...
关键字:XMLHelp

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;

}

责任编辑:admin
相关文章