| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403 |
- using System;
- using System.IO;
- using System.Collections.Generic;
- using System.Collections.Specialized;
- using System.Text;
- using System.Xml;
- using System.Xml.Schema;
- using System.Xml.Xsl;
- using System.Xml.XPath;
- using System.Data.OleDb;
- using System.Text.RegularExpressions;
- namespace com.cloudsoft.utils
- {
- /// <summary>
- /// Class contains methods for constructing and querying XML doms
- /// </summary>
- ///
- public class XMLHelper
- {
- // Declare module level variables
- /// <summary>The Node that this XMLHelper wraps</summary>
- protected XmlNode omNode;
- protected Boolean isValidXml = true;
- public String ValidationError;
- private static String _QUOTE = "\"";
- private Regex _DatePattern = null;
- private Regex _DoublePattern = null;
- internal OleDbConnection _con = null;
- #region Constructors
- /// <summary>Creates a new instance of XMLHelper </summary>
- public XMLHelper()
- {
- }
- /// <summary>
- /// Creates a new instance of XMLHelper with the base node set
- /// </summary>
- /// <param name="zRoot">The root node to create or an XML Document to load</param>
- public XMLHelper(String zRoot)
- {
- if (zRoot.Contains("<") || zRoot.Contains("<") || zRoot.Contains("\\"))
- //WADS: Cross site scripting...
- load(zRoot);
- else
- //WADS: XPath Injection...
- createRoot(zRoot);
- }
- public XMLHelper(StringBuilder zRoot)
- {
- load(zRoot);
- }
- public XMLHelper(Stream stream)
- {
- load(stream);
- }
- /// <summary>
- /// Creates a new instance of XMLHelper with the base node set
- /// </summary>
- /// <param name="oNode">The base node to set</param>
- public XMLHelper(XmlNode oNode)
- {
- omNode = oNode;
- }
- /// <summary>
- /// Creates a new instance of XMLHelper with the base node set to the first child of the Document
- /// </summary>
- /// <param name="oDoc">Document to base this XMLHelper on</param>
- public XMLHelper(XmlDocument oDoc)
- {
- omNode = (XmlNode)oDoc.DocumentElement;
- }
- #endregion
- #region IO & Save Methods
- /// <summary>
- /// Saves the dom to the specified path. Always overwrites anything already there.
- /// </summary>
- /// <param name="path">The path to save to.</param>
- public void SaveAs(String path)
- {
- try
- {
- //Overwrite any existing files...
- FileInfo fi = new FileInfo(path);
- if (fi.Exists)
- fi.Delete();
- }
- catch
- {
- //If you can't delete the file then don't try and overwrite it...
- return;
- }
- StreamWriter sw = new StreamWriter(path);
- try
- {
- //Set up a stream...
- sw.AutoFlush = true;
- //Write to the stream and close it...
- sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
- sw.Write(this.getXML());
- }
- finally
- {
- sw.Close();
- sw.Dispose();
- }
- }
- #endregion
- #region "Helper" methods
- /// <summary>
- /// Creates a Standard Request DOM
- /// </summary>
- /// <param name="zType">The type of request</param>
- /// <param name="zMudID">The mud id</param>
- /// <param name="zSystem">The system id</param>
- /// <returns></returns>
- public XMLHelper createStandardRequest(String zType, String zMudID, String zSystem)
- {
- return createStandardRequest(zType, zMudID, zSystem, zMudID);
- }
- /// <summary>
- /// Handles delegation
- /// </summary>
- /// <param name="zType"></param>
- /// <param name="zMudID"></param>
- /// <param name="zSystem"></param>
- /// <param name="UserLogon"></param>
- /// <returns></returns>
- public XMLHelper createStandardRequest(String zType, String zMudID, String zSystem, String UserLogon)
- {
- this.createRoot("request");
- this.appendAttribute("type", zType);
- this.appendNode("mud_id", zMudID);
- this.appendNode("system", zSystem);
- string zDeligateUser = UserLogon;
- string[] aSplit = zDeligateUser.Split("\\".ToCharArray());
- zDeligateUser = aSplit[aSplit.Length - 1].ToUpper();
- if (zMudID != zDeligateUser)
- this.appendNode("delegate_id", zDeligateUser);
- return this;
- }
- #endregion
- #region Dom Manipulation
- /// <summary>
- /// Creates the root Node
- /// </summary>
- /// <param name="zRootName">The name of the root node</param>
- public void createRoot(String zRootName)
- {
- //WADS: XPath Injection...
- this.load("<" + zRootName + "/>");
- }
- /// <summary>
- /// Appends a node to the dom
- /// </summary>
- /// <param name="vNodeName">The name of the new node</param>
- /// <returns>Returns an XMLHelper of the new Node</returns>
- public XMLHelper appendNode(String vNodeName)
- {
- XmlDocument oDoc = omNode.OwnerDocument;
- XmlNode oNewNode = oDoc.CreateElement(vNodeName);
- omNode.AppendChild(oNewNode);
- XMLHelper oHelper = new XMLHelper(oNewNode);
- return oHelper;
- }
- /// <summary>
- /// Appends a node to the dom and sets it's value
- /// </summary>
- /// <param name="vNodeName">The name of the new node</param>
- /// <param name="zValue">The value to set the new node</param>
- /// <returns>Returns the XMLHelper for the new node</returns>
- public XMLHelper appendNode(String vNodeName, Object zValue)
- {
- XmlDocument oDoc = omNode.OwnerDocument;
- XmlNode oNewNode = oDoc.CreateElement(vNodeName);
- oNewNode.AppendChild(oDoc.CreateTextNode(zValue == null ? "" : zValue.ToString()));
- omNode.AppendChild(oNewNode);
- XMLHelper oHelper = new XMLHelper(oNewNode);
- return oHelper;
- }
- /// <summary>
- /// Appends an XMLHelper dom
- /// </summary>
- /// <param name="oDOM">The DOM to append to this DOM</param>
- /// <returns>Returns the XMLHelper for the new node</returns>
- public XMLHelper appendNode(XMLHelper oDOM)
- {
- XmlNode oNew = omNode.OwnerDocument.ImportNode(oDOM.omNode, true);
- omNode.AppendChild(oNew);
- return new XMLHelper(oNew);
- }
- /// <summary>
- /// Appends a NameValueCollection to the DOM as Nodes
- /// </summary>
- /// <param name="oCol">The DOM to append to this DOM</param>
- public void appendNode(NameValueCollection oCol)
- {
- // Iterate through the collection and add
- // each name value pair to the dom
- for (int i = 0; i < oCol.Count; i++)
- {
- String zName = oCol.GetKey(i);
- String[] pValues = oCol.GetValues(i);
- for (int j = 0; j < pValues.Length; j++)
- appendNode(zName, pValues[j]);
- }
- }
- /// <summary>
- /// Appends an array of XMLHelpers
- /// </summary>
- /// <param name="oNodes">The Nodelist to append to the existing DOM</param>
- public void appendNode(XMLHelper[] oNodes)
- {
- for (int i = 0; i < oNodes.Length; i++)
- appendNode(oNodes[i]);
- }
- /// <summary>
- /// Appends an attribute to the dom and sets it's value
- /// </summary>
- /// <param name="zNodeName">The name of the new node</param>
- /// <param name="zValue">The value to set the new node</param>
- public void appendAttribute(String zNodeName, String zValue)
- {
- // Attr oAttr = omNode.getOwnerDocument().createAttribute(zNodeName);
- // oAttr.setNodeValue(zValue);
- // omNode.appendChild(oAttr);
- XmlElement oNode = (XmlElement)omNode;
- oNode.SetAttribute(zNodeName, zValue);
- }
- /// <summary>
- /// Retrieved the root node of a XMLHelper dom
- /// </summary>
- /// <returns>Returns the Root Node for this XMLHelper DOM</returns>
- public XMLHelper getRootNode()
- {
- return new XMLHelper(omNode.OwnerDocument);
- }
- public void appendXPathNode(String zXPath, String zValue)
- {
- appendXPathNode(zXPath, zValue, true);
- }
- /// <summary>
- /// Appends a node/attribute based on an XPath (like alias names in SQL)
- /// </summary>
- /// <param name="zXPath">The name of the new node/attribute in XPath syntax</param>
- /// <param name="zValue">The value to set the new node</param>
- public void appendXPathNode(String zXPath, String zValue, Boolean AlwaysAddNewNode)
- {
- try
- {
- int i;
- XmlNode oOrig = omNode;
- // Split the Name by "/"
- String[] arrNodes = zXPath.Split(new char[] { '/' });
- for (i = 0; i < arrNodes.Length - 1; i++)
- {
- XmlNode oNode = omNode.SelectSingleNode(arrNodes[i]);
- if (oNode == null)
- omNode = appendNode(arrNodes[i]).omNode;
- else
- omNode = oNode;
- }
- if (arrNodes[i].StartsWith("@"))
- appendAttribute(arrNodes[i].Substring(1), zValue);
- else
- {
- if (AlwaysAddNewNode)
- {
- appendNode(arrNodes[i], zValue);
- }
- else
- {
- if (this.nodeCount(arrNodes[i]) > 0)
- {
- this.getNode(arrNodes[i]).setValue(zValue);
- }
- else
- {
- appendNode(arrNodes[i], zValue);
- }
- }
- }
- omNode = oOrig;
- }
- catch (Exception ex)
- {
- System.Console.WriteLine(ex.Message);
- }
- }
- /// <summary>
- /// Removes a node given the nodename
- /// </summary>
- /// <param name="zNodeName">The name of node to remove</param>
- public void removeNode(String zNodeName)
- {
- try
- {
- XmlNode oTempNode = omNode.SelectSingleNode(zNodeName);
- if (oTempNode != null)
- oTempNode.ParentNode.RemoveChild(oTempNode);
- }
- catch
- {
- // Do nothing if we can't remove the node
- }
- }
- #endregion
- #region Serialisation
- /// <summary>
- /// Searalises the current tree from the current Node to a Writer (like Resonse.Output)
- /// </summary>
- /// <param name="oWriter">The Writer to write the XML to (eg. Resonse.Output)</param>
- public void serializeNode(TextWriter oWriter)
- {
- try
- {
- serializeNode(omNode, oWriter);
- }
- catch (Exception ex)
- {
- System.Console.WriteLine(ex.Message);
- }
- }
- /// <summary>
- /// Serializes the node.
- /// </summary>
- /// <param name="oNode">The node.</param>
- /// <param name="oWriter">The writer.</param>
- private void serializeNode(XmlNode oNode, TextWriter oWriter)
- {
- try
- {
- oWriter.Write(oNode.OuterXml);
- }
- catch (Exception ex)
- {
- System.Console.WriteLine(ex.Message);
- }
- }
- /// <summary>
- /// Serializes the node.
- /// </summary>
- /// <param name="oNode">The node.</param>
- /// <returns>An XML String</returns>
- private String serializeNode(XmlNode oNode)
- {
- try
- {
- return (oNode.OuterXml);
- }
- catch (Exception ex)
- {
- System.Console.WriteLine(ex.Message);
- return ("");
- }
- }
- public String getJSON()
- {
- StringWriter stringOut = new StringWriter();
- getJSON(stringOut);
- return (stringOut.ToString());
- }
- public void getJSON(TextWriter oOut)
- {
- oOut.Write("{");
- getJSON(omNode.OwnerDocument.FirstChild, false, oOut);
- oOut.Write("}");
- }
- private void getJSON(XmlNode oNode, Boolean isArray, TextWriter oOut)
- {
- String zName = oNode.Name;
- if (zName.Equals("#text")) zName = "$";
- if (!isArray)
- oOut.Write(_QUOTE + zName + _QUOTE + ":");
- if (isJSONArray(oNode.ChildNodes))
- {
- oOut.Write("[");
- getJSON(oNode.ChildNodes, true, oOut);
- oOut.Write("]");
- }
- else if (oNode.NodeType == XmlNodeType.Attribute)
- {
- oOut.Write(getJSONValue(oNode.Value));
- }
- else if (!oNode.HasChildNodes && (oNode.Attributes == null || oNode.Attributes.Count == 0))
- {
- if (oNode.Value == null)
- oOut.Write("null");
- else
- oOut.Write(getJSONValue(oNode.Value));
- }
- else if (oNode.Attributes.Count == 0 && oNode.ChildNodes.Count == 1 && !oNode.FirstChild.HasChildNodes)
- {
- oOut.Write(getJSONValue(oNode.FirstChild.Value));
- }
- else
- {
- oOut.Write("{");
- getJSON(oNode.Attributes, oOut);
- if (oNode.Attributes.Count > 0 && oNode.ChildNodes.Count > 0)
- oOut.Write(",");
- getJSON(oNode.ChildNodes, false, oOut);
- oOut.Write("}");
- }
- }
- private void getJSON(XmlNodeList oNodeList, Boolean isArray, TextWriter oOut)
- {
- for (int i = 0; i < oNodeList.Count; i++)
- {
- XmlNode oNode = oNodeList.Item(i);
- if (i > 0) oOut.Write(",");
- getJSON(oNode, isArray, oOut);
- }
- }
- private void getJSON(XmlAttributeCollection oNodeMap, TextWriter oOut)
- {
- for (int i = 0; i < oNodeMap.Count; i++)
- {
- XmlNode oNode = oNodeMap.Item(i);
- if (i > 0) oOut.Write(",");
- getJSON(oNode, false, oOut);
- }
- }
- private String getJSONValue(String zValue)
- {
- zValue = zValue.Trim();
- if (DatePattern().IsMatch(zValue))
- {
- DateTime matchDate = DateTime.Now;
- try { matchDate = DateTime.Parse(zValue); }
- catch (Exception ex) { }
- String ret = "new Date(" + matchDate.Year + "," + (matchDate.Month - 1) + "," + matchDate.Day;
- if (zValue.Length > 11)
- ret += "," + matchDate.Hour + "," + matchDate.Minute + "," + matchDate.Second;
- ret += ")";
- return ret;
- }
- else if (zValue.Length <= 10)
- {
- try { return int.Parse(zValue).ToString(); }
- catch (Exception ex) { }
- if (DoublePattern().IsMatch(zValue))
- return zValue;
- //try { return Double.Parse(zValue).ToString();}
- //catch (Exception ex) {}
- }
- return _QUOTE + zValue.Replace("\\", "\\\\").Replace("\"", "\\\"") + _QUOTE;
- }
- private Boolean isJSONArray(XmlNodeList oNodeList)
- {
- if (oNodeList.Count < 1 || (oNodeList.Count == 1 && (oNodeList.Item(0).Name + "s") != oNodeList.Item(0).ParentNode.Name)) return (false);
- String zName = oNodeList.Item(0).Name;
- for (int i = 0; i < oNodeList.Count; i++)
- {
- if (!oNodeList.Item(i).Name.Equals(zName))
- return (false);
- }
- return (true);
- }
- private Regex DatePattern()
- {
- if (_DatePattern == null)
- {
- _DatePattern = new Regex("^(([0-9])|([0-2][0-9])|([3][0-1]))-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\\d{4}.*", RegexOptions.IgnoreCase);
- }
- return _DatePattern;
- }
- private Regex DoublePattern()
- {
- if (_DoublePattern == null)
- {
- _DoublePattern = new Regex("^[-+]?[0-9]*\\.?[0-9]+$");
- }
- return _DoublePattern;
- }
- #endregion
- #region Load Methods
- /// <summary>
- /// Loads a string into the DOM or a file. Either an XML string or a file location may be used
- /// </summary>
- /// <param name="zXML">Either the XML as a string or a file location</param>
- /// <returns>Boolean indicating success or failure</returns>
- public Boolean load(String zXML)
- {
- try
- {
- XmlDocument oDOM = new XmlDocument();
- if (zXML.StartsWith("<") || zXML.StartsWith("<"))
- //WADS: XPath Injection...
- oDOM.LoadXml(zXML);
- else
- //WADS: XPath Injection...
- oDOM.Load(zXML);
- omNode = (XmlNode)oDOM.DocumentElement;
- return true;
- }
- catch (Exception ex)
- {
- throw new Exception("Can't load dom. Error: " + ex.Message);
- }
- }
- public Boolean load(Stream stream)
- {
- try
- {
- XmlDocument oDOM = new XmlDocument();
- oDOM.Load(stream);
- omNode = (XmlNode)oDOM.DocumentElement;
- return true;
- }
- catch (Exception ex)
- {
- throw new Exception("Can't load dom. Error: " + ex.Message);
- }
- }
- public Boolean load(StringBuilder zXML)
- {
- try
- {
- StringReader sr = new StringReader(zXML.ToString());
- XmlReader xr = XmlReader.Create(sr);
- XmlDocument oDOM = new XmlDocument();
- oDOM.Load(xr);
- omNode = (XmlNode)oDOM.DocumentElement;
- return true;
- }
- catch (Exception ex)
- {
- throw new Exception("Can't load dom. Error: " + ex.Message);
- }
- }
- public Boolean loadTSV(String zPath)
- {
- try
- {
- // Create an instance of StreamReader to read from a file.
- // The using statement also closes the StreamReader.
- this.createRoot("response");
- XMLHelper oRows = this.appendNode("rows");
- using (StreamReader sr = new StreamReader(zPath))
- {
- String[] aHeader = null;
- String line;
- // Read and display lines from the file until the end of
- // the file is reached.
- while ((line = sr.ReadLine()) != null)
- {
- // Get the header if we don't have it
- if (aHeader == null)
- {
- aHeader = line.Split('\t');
- }
- else
- {
- String[] aFields = line.Split('\t');
- int i = 0;
- XMLHelper oRow = oRows.appendNode("row");
- foreach (String zHeader in aHeader)
- oRow.appendNode(zHeader, aFields[i++]);
- }
- }
- }
- return true;
- }
- catch (Exception e)
- {
- // Let the user know what went wrong.
- throw new Exception("The file could not be read: " + e.Message);
- }
- }
- #endregion
- #region Get and Set Methods
- /// <summary>
- /// Retrieved the child nodes an XMLHelper dom
- /// </summary>
- /// <returns>Returns the Child nodes as an array</returns>
- public XMLHelper[] getChildNodes()
- {
- XmlNodeList oNodes = omNode.ChildNodes;
- XMLHelper[] arrNodes = new XMLHelper[oNodes.Count];
- for (int i = 0; i < oNodes.Count; i++)
- arrNodes[i] = new XMLHelper(oNodes.Item(i));
- return arrNodes;
- }
- public XMLHelper getFirstChild()
- {
- return new XMLHelper(omNode.FirstChild);
- }
- public DateTime getSQLDate(String zXPath)
- {
- return getDate(zXPath);
- }
- public DateTime getSQLDateTime(String zXPath)
- {
- return getDate(zXPath);
- }
- /// <summary>
- /// Gets the XML of the current node as a string
- /// </summary>
- /// <returns>Returns the XML of the current node as a string</returns>
- public String getXML()
- {
- return serializeNode(omNode);
- }
- /// <summary>
- /// Gets the InnerXML of the current node as a string
- /// </summary>
- /// <returns>Returns the InnerXML of the current node as a string</returns>
- public String getInnerXML()
- {
- return omNode.InnerXml;
- }
- /// <summary>
- /// Gets the XML of the root node as a string
- /// </summary>
- /// <returns>Returns the XML of the root node as a string</returns>
- public String getRootXML()
- {
- return omNode.OwnerDocument.OuterXml;
- }
- /// <summary>
- /// Get the parent XMLHelper
- /// </summary>
- /// <returns>Returns the Parent node as an XMLHelper object</returns>
- public XMLHelper getParent()
- {
- XMLHelper oHelper = new XMLHelper(omNode.ParentNode);
- return oHelper;
- }
- /// <summary>
- /// Returns the Name of a node or element
- /// </summary>
- /// <returns>The node name of the current node</returns>
- public String getName()
- {
- try
- {
- return omNode.Name;
- }
- catch (Exception)
- {
- return "";
- }
- }
- /// <summary>
- /// Returns the value of a node or element
- /// JF 12/2007 - Added a check for a null valued XMLHelper (with a null omNode)
- /// rather than relying on the exception handler.
- /// </summary>
- /// <returns>The nodevalue of the current node</returns>
- public String getValue()
- {
- if (omNode != null)
- {
- try
- {
- return omNode.InnerText;
- }
- catch (Exception)
- {
- return "";
- }
- }
- else
- {
- return "";
- }
- }
- /// <summary>
- /// Returns the value of a node or element as a string
- /// </summary>
- /// <param name="zXPath">A valid XPath to find a node</param>
- /// <returns>The nodevalue of the Node found as a string</returns>
- public String getValue(String zXPath)
- {
- return getNode(zXPath).getValue();
- }
- /// <summary>
- /// Returns the value of a node or element as a string
- /// </summary>
- /// <param name="zXPath">A valid XPath to find a node</param>
- /// <returns>The nodevalue of the Node found as a string</returns>
- public String getString(String zXPath)
- {
- return getValue(zXPath);
- }
- /// <summary>
- /// Returns the value of a node or element as a long
- /// </summary>
- /// <param name="zXPath">A valid XPath to find a node</param>
- /// <returns>The nodevalue of the Node found as a long</returns>
- public long getLong(String zXPath)
- {
- try
- {
- return Convert.ToInt64(getValue(zXPath).Trim());
- }
- catch (Exception)
- {
- return 0;
- }
- }
- /// <summary>
- /// Returns the value of a node or element as an int
- /// </summary>
- /// <param name="zXPath">A valid XPath to find a node</param>
- /// <returns>The nodevalue of the Node found as an int</returns>
- public int getInt(String zXPath)
- {
- try
- {
- String value = getValue(zXPath).Trim();
- if (value.Length > 0)
- {
- return Convert.ToInt32(value);
- }
- else
- {
- return 0;
- }
- }
- catch (Exception)
- {
- return 0;
- }
- }
- /// <summary>
- /// Returns the value of a node or element as a double
- /// </summary>
- /// <param name="zXPath">A valid XPath to find a node</param>
- /// <returns>The nodevalue of the Node found as a double</returns>
- public double getDouble(String zXPath)
- {
- try
- {
- return Convert.ToDouble(getValue(zXPath).Trim());
- }
- catch
- {
- return 0.0;
- }
- }
- /// <summary>
- /// Returns the value of a node or element as a DateTime Object
- /// </summary>
- /// <param name="zXPath">A valid XPath to find a node</param>
- /// <returns>The nodevalue of the Node found as a DateTime Object</returns>
- public DateTime getDate(String zXPath)
- {
- DateTime d = DateTime.MinValue;
- try
- {
- DateTime.TryParse(getValue(zXPath).Trim(), out d);
- }
- catch { }
- return d;
- }
- /// <summary>
- /// Returns the value of a node or element as a Boolean
- /// </summary>
- /// <param name="zXPath">A valid XPath to find a node</param>
- /// <returns>The nodevalue of the Node found as a Boolean</returns>
- public Boolean getBoolean(String zXPath)
- {
- String zVal = getValue(zXPath).ToUpper();
- return (zVal.Equals("Y") || zVal.Equals("YES") || zVal.Equals("TRUE"));
- }
- /// <summary>
- /// Returns the value of a node or element as either Y or N
- /// </summary>
- /// <param name="zXPath">A valid XPath to find a node</param>
- /// <returns>The nodevalue of the Node found as a Boolean</returns>
- public String getYN(String zXPath)
- {
- return (getBoolean(zXPath) ? "Y" : "N");
- }
- /// <summary>
- /// Returns an XMLHelper for a XPath
- /// </summary>
- /// <param name="zXPath">A valid XPath to find a node</param>
- /// <returns>XMLHelper for a XPath</returns>
- public XMLHelper getNode(String zXPath)
- {
- XmlNode oNode;
- try
- {
- oNode = omNode.SelectSingleNode(zXPath);
- return new XMLHelper(oNode);
- }
- catch
- {
- // JF 12/2007 - Don't just blindly return an empty XMLHelper if the getNode fails.
- // Should create an alternative function for this purpose if it is ever required.
- throw new Exception("Can't get node for xpath: " + zXPath);
- }
- }
- /// <summary>
- /// Returns an Array of XMLHelper objects for a XPath
- /// </summary>
- /// <param name="zXPath">A valid XPath to find a node</param>
- /// <returns>Array of XMLHelper object for a XPath</returns>
- public XMLHelper[] getNodes(String zXPath)
- {
- try
- {
- XmlNodeList oNodes = omNode.SelectNodes(zXPath);
- XMLHelper[] arrNodes = new XMLHelper[oNodes.Count];
- for (int i = 0; i < oNodes.Count; i++)
- arrNodes[i] = new XMLHelper(oNodes.Item(i));
- return arrNodes;
- }
- catch (Exception ex)
- {
- System.Console.WriteLine(ex.Message);
- return null;
- }
- }
- /// <summary>
- /// Gets a CSV string given an XPath
- /// </summary>
- /// <param name="zXPath">The XPath.</param>
- /// <returns>A CSV String</returns>
- public String getCSV(String zXPath)
- {
- StringWriter oSW = new StringWriter();
- XmlNodeList oNodes = omNode.SelectNodes(zXPath);
- for (int i = 0; i < oNodes.Count; i++)
- {
- if (i > 0)
- oSW.Write(',');
- oSW.Write(oNodes[i].InnerText);
- }
- return oSW.ToString();
- }
- /// <summary>
- /// Sets a Nodes value
- /// </summary>
- /// <param name="zNodeName">The name of the node to set</param>
- /// <param name="zValue">The value to set the node</param>
- public void setNode(String zNodeName, String zValue)
- {
- removeNode(zNodeName);
- appendNode(zNodeName, zValue);
- }
- /// <summary>
- /// Sets a Nodes value
- /// </summary>
- /// <param name="zNodeName">The name of the node to set</param>
- /// <param name="zValue">The value to set the node</param>
- public void setValue(String zValue)
- {
- omNode.InnerText = zValue;
- }
- /// <summary>
- /// Sets an attribute value
- /// </summary>
- /// <param name="zNodeName">The name of the attribute to set</param>
- /// <param name="zValue">The value to set the attribute</param>
- public void setAttribute(String zAttributeName, String zValue)
- {
- omNode.Attributes[zAttributeName].Value = zValue;
- }
- public void setAttribute(String zAttributeName, Int32 iValue)
- {
- omNode.Attributes[zAttributeName].Value = iValue.ToString();
- }
- /// <summary>
- /// Gets the numbers of rows given an XPath
- /// </summary>
- /// <param name="zXPath">The Xpath to get the nodecount for</param>
- /// <returns>The number of nodes for the given Xpath</returns>
- public int nodeCount(String zXPath)
- {
- try
- {
- XmlNodeList oNodes = omNode.SelectNodes(zXPath);
- return (oNodes.Count);
- }
- catch
- {
- return 0;
- }
- }
- public XPathNodeIterator getIterator(String sourceNodePath)
- {
- XPathNavigator nav = omNode.CreateNavigator();
- XPathExpression expression = nav.Compile(sourceNodePath);
- return nav.Select(expression);
- }
- #endregion
- #region Testing
- /// <summary>
- /// Test Harness
- /// </summary>
- /// <param name="args">the command line arguments</param>
- public static void Main(String[] args)
- {
- // Test simple Load
- XMLHelper oDOM = new XMLHelper();
- // Test creating a DOM by handing and manipulating it
- oDOM.createStandardRequest("test_type", "PYL38997", "CIMS");
- oDOM.appendNode("test", "value");
- System.Console.WriteLine("test:" + oDOM.getValue("test"));
- System.Console.WriteLine("@type:" + oDOM.getValue("@type"));
- oDOM.removeNode("test");
- System.Console.WriteLine(oDOM.getRootXML());
- // More manipulation
- oDOM.appendNode("test", "value");
- oDOM.setNode("test", "new Value");
- oDOM = oDOM.appendNode("groups");
- for (int i = 0; i < 10; i++)
- oDOM.appendNode("group").appendAttribute("id", Convert.ToString(i));
- // Test getNodes
- XMLHelper[] oNodes = oDOM.getNodes("//group");
- for (int i = 0; i < oNodes.Length; i++)
- System.Console.WriteLine(oNodes[i].getXML());
- System.Console.WriteLine(oDOM.getRootXML());
- // Test appending an entirely new DOM
- XMLHelper oNew = new XMLHelper("new");
- oNew.appendNode("test", "40213423");
- oDOM.appendNode(oNew);
- System.Console.WriteLine(oDOM.getRootXML());
- // Test appending a Nodelist
- oNew.appendNode(oNodes);
- System.Console.WriteLine(oNew.getRootXML());
- System.Console.WriteLine(oDOM.getRootNode().getChildNodes().Length);
- System.Console.WriteLine(oDOM.omNode.OwnerDocument.GetElementsByTagName("group").Count);
- System.Console.WriteLine(oDOM.getParent().getNode("group").getXML());
- XMLHelper o = new XMLHelper("response");
- o.appendXPathNode("customer/@id", "1");
- o.appendXPathNode("customer/name/first", "john");
- o.appendXPathNode("customer/name/last", "doe");
- o.appendNode("date", "01-jan-2005");
- o.appendNode("empty_date", "");
- System.Console.WriteLine(o.getDate("date"));
- System.Console.WriteLine(o.getDate("empty_date"));
- System.Console.WriteLine(o.getRootXML());
- System.Console.WriteLine(o.omNode.ChildNodes.Count);
- System.Console.WriteLine("Inner : " + o.getInnerXML());
- }
- #endregion
- #region Distinct XML
- /// <summary>
- /// Appends a distinct set of the specified nodes to the current document.
- /// See description for other appendDistinct overload (Example 1).
- /// </summary>
- public void appendDistinct(String sourceNodePath, String keyAttribute, String resultRoot)
- {
- appendDistinct(sourceNodePath, keyAttribute, resultRoot, null, "");
- }
- /// <summary>
- /// High performance option for append distinct.
- /// Allows direct access with an iterator.
- /// Useful if adding multiple distincts from the same source rowset.
- /// </summary>
- /// <param name="incomingIterator"></param>
- /// <param name="keyAttribute"></param>
- /// <param name="resultRoot"></param>
- /// <param name="additionalAttributes"></param>
- /// <param name="resultNodesName"></param>
- /// <param name="UseNodes">Forces the iterator to select nodes rather than attributes</param>
- public void appendDistinct(XPathNodeIterator incomingIterator, String keyAttribute, String resultRoot, String[] additionalAttributes, String resultNodesName, Boolean UseNodes)
- {
- string value;
- string attribute;
- SortedList<string, object> ids = new SortedList<string, object>();
- MemoryStream ms = new MemoryStream();
- XmlTextWriter xmlWriter = new XmlTextWriter(ms, Encoding.UTF8);
- xmlWriter.WriteStartElement(resultRoot);
- XPathNodeIterator iterator = incomingIterator.Clone();
- while (iterator.MoveNext())
- {
- if (UseNodes)
- attribute = keyAttribute;
- else
- attribute = "@" + keyAttribute;
- value = iterator.Current.SelectSingleNode(attribute).Value;
- if (!ids.ContainsKey(value))
- {
- if (additionalAttributes != null)
- {
- xmlWriter.WriteStartElement(resultNodesName);
- xmlWriter.WriteAttributeString(keyAttribute, value);
- ids.Add(value, null);
- foreach (String extraNode in additionalAttributes)
- {
- if (UseNodes)
- attribute = extraNode;
- else
- attribute = "@" + extraNode;
- xmlWriter.WriteAttributeString(extraNode, iterator.Current.SelectSingleNode(attribute).Value);
- }
- xmlWriter.WriteEndElement();
- }
- else
- {
- xmlWriter.WriteElementString(keyAttribute, value);
- ids.Add(value, null);
- }
- }
- }
- xmlWriter.WriteEndElement();
- xmlWriter.Flush();
- ms.Seek(0, System.IO.SeekOrigin.Begin);
- XmlDocument distinct = new XmlDocument();
- distinct.Load(ms);
- xmlWriter.Close();
- omNode.AppendChild(omNode.OwnerDocument.ImportNode(distinct.DocumentElement, true));
- }
- public void appendDistinct(XPathNodeIterator incomingIterator, String keyAttribute, String resultRoot, String[] additionalAttributes, String resultNodesName)
- {
- appendDistinct(incomingIterator, keyAttribute, resultRoot, additionalAttributes, resultNodesName, false);
- }
- /// <summary>
- /// Appends a distinct set of the specified nodes to the current document.
- /// If additionalAttributes is null then resultNodesName is not used and the results will look
- /// like the first example. With additionalAttributes
- /// </summary>
- /// <param name="sourceNodePath">XPath to the nodes to be distincted.</param>
- /// <param name="keyAttribute">Attribute to key on for determining uniqueness.</param>
- /// <param name="resultRoot">Name of the root node to create and append the distinct nodes to.</param>
- /// <param name="additionalAttributes">Additional attributes to include in the distinct items.</param>
- /// <param name="resultNodesName">Name of individual result nodes.</param>
- /// <param name="UseNodes">Use nodes instead of attributes for the data.</param>
- ///
- /// <example >
- ///
- /// Source:
- /// <activities>
- /// <activity customer_id="1" name="Phil" type="M"/>
- /// <activity customer_id="1" name="Phil" type="C"/>
- /// <activity customer_id="2" name="Trev" type="M"/>
- /// </activities>
- ///
- /// Example 1: appendDistinct("activities/activity", "customer_id", "customer_ids")
- /// <customer_ids execution_duration="0">
- /// <customer_id>1</customer_id>
- /// <customer_id>2</customer_id>
- /// </customer_ids>
- ///
- /// Example 2: appendDistinct("activities/activity", "customer_id", "customers", new string[] { "name" }, "customer" )
- /// <customers execution_duration="0">
- /// <customer customer_id="1" name="Phil" />
- /// <customer customer_id="2" name="Trev" />
- /// </customers>
- ///
- /// </example>
- public void appendDistinct(String sourceNodePath, String keyAttribute, String resultRoot, String[] additionalAttributes, String resultNodesName, Boolean UseNodes)
- {
- DateTime startTime = DateTime.Now;
- XPathNavigator nav = omNode.CreateNavigator();
- XPathExpression expression = nav.Compile(sourceNodePath);
- XPathNodeIterator iterator = nav.Select(expression);
- appendDistinct(iterator, keyAttribute, resultRoot, additionalAttributes, resultNodesName, UseNodes);
- TimeSpan ExecutionDuration = DateTime.Now - startTime;
- this.getNode(resultRoot).appendAttribute("execution_duration", ExecutionDuration.TotalMilliseconds.ToString());
- }
- public void appendDistinct(String sourceNodePath, String keyAttribute, String resultRoot, String[] additionalAttributes, String resultNodesName)
- {
- appendDistinct(sourceNodePath, keyAttribute, resultRoot, additionalAttributes, resultNodesName, false);
- }
- #endregion
- #region Validation
- public string validateXML(String schema)
- {
- StringReader srXml = new StringReader(getRootXML());
- XmlValidatingReader vr;
- XmlTextReader tr;
- XmlSchemaCollection schemaCol = new XmlSchemaCollection();
- XMLHelper oResponse = new XMLHelper("response");
- try
- {
- schemaCol.Add(null, schema);
- isValidXml = true;
- // Read the xml.
- tr = new XmlTextReader(srXml);
- // Create the validator.
- vr = new XmlValidatingReader(tr);
- // Set the validation tyep.
- vr.ValidationType = ValidationType.Auto;
- // Add the schema.
- if (schemaCol != null)
- {
- vr.Schemas.Add(schemaCol);
- }
- // Set the validation event handler.
- vr.ValidationEventHandler +=
- new ValidationEventHandler(ValidationCallBack);
- // Read the xml schema.
- while (isValidXml && vr.Read())
- {
- }
- vr.Close();
- oResponse.appendNode("valid", "true");
- return oResponse.getRootXML();
- }
- catch (Exception ex)
- {
- oResponse.appendNode("valid", "false");
- oResponse.appendNode("error", ex.Message);
- ValidationError = ex.Message;
- return oResponse.getRootXML();
- }
- finally
- {
- // Clean up...
- vr = null;
- tr = null;
- schemaCol = null;
- }
- }
- public Boolean validateUsing(String schema)
- {
- StringReader srXml = new StringReader(getRootXML());
- XmlValidatingReader vr;
- XmlTextReader tr;
- XmlSchemaCollection schemaCol = new XmlSchemaCollection();
- schemaCol.Add(null, schema);
- isValidXml = true;
- try
- {
- // Read the xml.
- tr = new XmlTextReader(srXml);
- // Create the validator.
- vr = new XmlValidatingReader(tr);
- // Set the validation tyep.
- vr.ValidationType = ValidationType.Auto;
- // Add the schema.
- if (schemaCol != null)
- {
- vr.Schemas.Add(schemaCol);
- }
- // Set the validation event handler.
- vr.ValidationEventHandler +=
- new ValidationEventHandler(ValidationCallBack);
- // Read the xml schema.
- while (isValidXml && vr.Read())
- {
- }
- vr.Close();
- return isValidXml;
- }
- catch (Exception ex)
- {
- ValidationError = ex.Message;
- return false;
- }
- finally
- {
- // Clean up...
- vr = null;
- tr = null;
- }
- }
- private void ValidationCallBack(object sender,
- ValidationEventArgs args)
- {
- // The xml does not match the schema.
- isValidXml = false;
- ValidationError = args.Message;
- }
- #endregion
- #region XSL Transformation
- /// <summary>
- /// Transforms the current DOM using the XSL and returns an XMLHelper DOM
- /// </summary>
- /// <param name="zXSL">The XSL for the transform</param>
- /// <returns>XMLHelper DOM with the result of the transform</returns>
- public XMLHelper transform(String zXSL)
- {
- return transform(zXSL, new Dictionary<string, string>());
- }
- /// <summary>
- /// Transforms the current DOM using the XSL to a TextWriter
- /// </summary>
- /// <param name="zXSL">The XSL for the transform</param>
- /// <param name="oOut">Thre Textwriter to output to</param>
- public void transform(String zXSL, TextWriter oOut)
- {
- transform(zXSL, new Dictionary<string, string>(), oOut);
- }
- public XMLHelper transform(Stream oXSL)
- {
- return transform(oXSL, new Dictionary<string, string>());
- }
- public XMLHelper transform(Stream oXSL, Dictionary<string, string> aParams)
- {
- StringWriter oText = new StringWriter();
- transform(oXSL, aParams, oText);
- return new XMLHelper(oText.GetStringBuilder());
- }
- /// <summary>
- /// Transforms the current DOM using the XSL to a TextWriter
- /// </summary>
- /// <param name="zXSL">The XSL for the transform</param>
- /// <param name="aParams">String Array of paramters to pass to the XSL</param>
- /// <param name="oOut">Thre Textwriter to output to</param>
- public void transform(String zXSL, Dictionary<string, string> aParams, TextWriter oOut)
- {
- Stream oXSL = new FileStream(zXSL, FileMode.Open);
- transform(oXSL, aParams, oOut);
- }
- public void transform(Stream oXSL, Dictionary<string, string> aParams, TextWriter oOut)
- {
- XslCompiledTransform transformer = new XslCompiledTransform();
- XsltArgumentList args = new XsltArgumentList();
- foreach (string key in aParams.Keys)
- {
- args.AddParam(key, "", aParams[key]);
- }
- //Having to specify settings for the load, due to embedded script usage...
- XsltSettings xsltSettings = new XsltSettings(true, true);
- XmlUrlResolver xmlResolver = new XmlUrlResolver();
- XmlReader reader = XmlReader.Create(oXSL);
- transformer.Load(reader, xsltSettings, xmlResolver);
- //transformer.Load(oXSL, );
- if (omNode.ParentNode == omNode.OwnerDocument)
- transformer.Transform(omNode.OwnerDocument, args, oOut);
- else
- transformer.Transform(omNode, args, oOut);
- }
- /// <summary>
- /// Transforms the current DOM using the XSL and returns an XMLHelper DOM
- /// </summary>
- /// <param name="zXSL">The XSL for the transform</param>
- /// <param name="aParams">String Array of paramters to pass to the XSL</param>
- /// <returns>XMLHelper DOM with the result of the transform</returns>
- public XMLHelper transform(String zXSL, Dictionary<string, string> aParams)
- {
- //try
- //{
- StringWriter oText = new StringWriter();
- transform(zXSL, aParams, oText);
- return new XMLHelper(oText.GetStringBuilder());
- //}
- //catch (Exception ex)
- //{
- // System.Console.WriteLine(ex.Message);
- // return null;
- //}
- }
- #endregion
- }
- }
|