5,665,355 members and growing! (16,246 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

Quick Xml Read and Write Adapters for C#

By ColinBashBash

For cleaner code. Easy to add methods as needed
C#, Windows, .NET, Visual Studio, ASP.NET, Dev

Posted: 27 Sep 2005
Updated: 9 Mar 2006
Views: 35,727
Bookmarked: 22 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
11 votes for this Article.
Popularity: 2.28 Rating: 2.19 out of 5
6 votes, 54.5%
1
1 vote, 9.1%
2
1 vote, 9.1%
3
2 votes, 18.2%
4
1 vote, 9.1%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

XML Adapters -> Simple-Reader, Writer

Update Notes:
- added an XML Adapter Reader Collection and some extra constructors / methods.
- added an attribute writer for XmlWriterAdapter

Update Clarifications
- These adapters are just to simplify things. The XmlDocument in ASP .Net is very verbose.
- If you want to open and modify a pre-existing XmlDocument, you'll have to write your own adapter. This doesn't really happen that often in what I do.

Simple stuff. These are just adapters to help separate xml document from the business logic. The Reader allows you to grab a child's value or a child's attribute. Also allows you to check to see if child exists. Lets you grab a node subset --> basically, if you sent it "childList" it would return a NodeList of grandChild's:

<currNode>
  <child1/>
  <child2/>
  <childList>
     <grandchild>
        
        
     </grandchild>
     <grandchild>
        
        
     </grandchild>
  </childList>
  <child4/>
</currNode>

-------------
The writer allows for creating nodes with values.
-- (I just added the attribute part. Not sure if it works, but it compiles.)
Also allows for appending those nodes. Lots of overloaded methods. Allows for printing the document.

Add & change as you will

#region XmlWriterAdapter and XmlReaderAdapter

#region XmlReaderAdapter
/// <summary>

/// Allows Easy Reading from XmlNodes

/// </summary>

public class XmlReaderAdapter {
	#region Attributes
	private XmlNode currNode;
	#endregion

	#region Constructors
	public XmlReaderAdapter(XmlNode currNode){
		this.currNode = currNode;
	}
	public XmlReaderAdapter(XmlDocument doc):this(doc.FirstChild){
	}
	#endregion

	#region Getting text and attribute values
	/// <summary>

	/// Get child value of a node.

	/// </summary>

	public string this[string child]{
		get{
			return currNode.SelectSingleNode("child::" + child).InnerText;
		}
	}
	/// <summary>

	/// Get child attribute.

	/// </summary>

	public string this[string child, string attribute]{
		get{
			return currNode.SelectSingleNode("child::" + child).Attributes[attribute].Value;
		}
	}
	#endregion

	#region Check if child exists
	/// <summary>

	/// Return whether child value exists.

	/// </summary>

	/// <param name="child"></param>

	/// <returns></returns>

	public bool hasChildValue(string child){
		return (hasChild(child) && (this[child].Length>0));
	}
	public bool hasChild(string child){
		return (this.currNode.SelectSingleNode("child::"+child)!=null);
	}
	#endregion

	#region Get Sub-Nodes - Old version
	/// <summary>

	/// Get Child node collection from a wrapper name - old version

	/// </summary>

	/// <param name="collectionWrapperChild"></param>

	/// <returns></returns>

	public XmlNodeList getSubNodeCollection(string collectionWrapperChild){
		return currNode.SelectSingleNode("child::" + collectionWrapperChild).ChildNodes;
	}
	#endregion

	#region Get SubNode / Children Adapter Collections - new version
	/// <summary>

	/// Get Child node collection from a wrapper name

	/// </summary>

	/// <param name="collectionWrapperChild"></param>

	/// <returns></returns>

	public XmlReaderAdapterCollection getSubNodeAdapterCollection(string collectionWrapperChild){
		return new XmlReaderAdapterCollection(currNode.SelectSingleNode("child::" + collectionWrapperChild).ChildNodes);
	}
	/// <summary>

	/// Get All Child nodes

	/// </summary>

	/// <param name="collectionWrapperChild"></param>

	/// <returns></returns>

	public XmlReaderAdapterCollection getAllChildren(){
		return new XmlReaderAdapterCollection(currNode.ChildNodes);
	}

	#endregion
}
#endregion

#region XmlReaderAdapterCollection
/// <summary>

/// Provides a strongly typed collection of XmlReaderAdapter objects.

/// </summary>

[Serializable()]
public class XmlReaderAdapterCollection : CollectionBase{
	/// <summary>

	/// Creates Default XmlReaderAdapterCollection

	/// </summary>

	public XmlReaderAdapterCollection(){
	}
	/// <summary>

	/// Creates XmlReaderAdapterCollection from a list of nodes

	/// </summary>

	public XmlReaderAdapterCollection(XmlNodeList nodes){
		foreach (XmlNode node in nodes){
			this.Add(new XmlReaderAdapter(node));
		}
	}/// <summary>

	/// Returns a XmlReaderAdapter object from the specified ordinal position within the collection.

	/// </summary>

	public XmlReaderAdapter this[int index]{
		get{
			return (XmlReaderAdapter)List[index];
		}
		set{
			List[index] = value;
		}
	}
	/// <summary>

	/// Adds a VersionCriteria to the VersionCriteriaCollection.

	/// </summary>

	/// <param name="value">The XmlReaderAdapter object to add to the collection.</param>

	/// <returns>The position within the collection that the XmlReaderAdapter object was added.</returns>

	public int Add(XmlReaderAdapter value){
		return(List.Add(value));
	}

	/// <summary>

	/// Determines the index in the XmlReaderAdapterCollection of the XmlReaderAdapter object specified.

	/// </summary>

	/// <param name="value">The VersionCriteria object to locate within the collection.</param>

	/// <returns>The index of the VersionCriteria object; if not found returns -1.</returns>

	public int IndexOf(XmlReaderAdapter value){
		return(List.IndexOf(value));
	}

	/// <summary>

	/// Adds the VersionCriteria object at the specified ordinal position in the collection.

	/// </summary>

	/// <param name="index">The zero based index at which the XmlReaderAdapter object should be added.</param>

	/// <param name="value">The XmlReaderAdapter to be added to the XmlReaderAdapterCollection.</param>

	public void Insert(int index, XmlReaderAdapter value){
		List.Insert(index, value);
	}

	/// <summary>

	/// Removes the XmlReaderAdapter object from the XmlReaderAdapterCollection.

	/// </summary>

	/// <param name="value">The XmlReaderAdapter object to remove.</param>

	public void Remove(XmlReaderAdapter value){
		List.Remove(value);
	}

	/// <summary>

	/// Determines if the XmlReaderAdapterCollection contains the specified XmlReaderAdapter object.

	/// </summary>

	/// <param name="value">The XmlReaderAdapter to search for.</param>

	/// <returns>true if the XmlReaderAdapter object is found in the collection; false if not.</returns>

	public bool Contains(XmlReaderAdapter value){
		return(List.Contains(value));
	}
}
#endregion

#region XmlWriterAdapter
/// <summary>

/// Allows Easy Writing of an XmlDocument

/// </summary>

public class XmlWriterAdapter{
	#region Properties and Attributes
	private XmlDocument doc;
	private string docNamespace;
	private XmlNode rootNode;
	/// <summary>

	/// Allows you to retrieve the RootNode, so you can append to the root if needed

	/// </summary>

	public XmlNode RootNode{
		get{
			return this.rootNode;
		}
	}
	/// <summary>

	/// Allows you to retrieve the XmlDocument in case you need to do something not

	/// defined here.

	/// </summary>

	public XmlDocument Doc{
		get{
			return this.doc;
		}
	}
	#endregion

	#region Constructors
	/// <summary>

	/// Creates a XmlWriterAdapter with no namespace (THIS IS NORMAL)

	/// </summary>

	/// <param name="rootNodeName"></param>

	public XmlWriterAdapter(string rootNodeName):this(string.Empty,rootNodeName){
	}
	/// <summary>

	/// Creates a XmlWriterAdapter with a namespace (CURRENTLY NOT USED)

	/// </summary>

	/// <param name="docNamespace"></param>

	/// <param name="rootNodeName"></param>

	public XmlWriterAdapter(string docNamespace, string rootNodeName){
		this.docNamespace = docNamespace;
		this.doc = new XmlDocument();
		rootNode = MakeAndSetElement(rootNodeName);
		doc.AppendChild(rootNode);
	}
	#endregion

	#region Creating Elements with inner text
	/// <summary>

	/// Creates and returns an element with the given name and NO value.

	/// </summary>

	/// <param name="name"></param>

	/// <returns></returns>

	public XmlNode MakeAndSetElement(string name){
		return doc.CreateNode(XmlNodeType.Element, name, docNamespace);
	}
	/// <summary>

	/// Creates and returns an element with the given name and value

	/// </summary>

	/// <param name="name"></param>

	/// <param name="value"></param>

	/// <returns></returns>

	public XmlNode MakeAndSetElement(string name, string value){
		XmlNode field = MakeAndSetElement(name);
		//if (value != string.Empty){

		field.InnerText = value;
		//}

		return field;
	}
	#endregion

	#region Add Attribute
	/// <summary>

	/// Makes and sets an attribute. 

	/// </summary>

	/// <param name="name"></param>

	/// <param name="value"></param>

	/// <param name="parent"></param>

	public void MakeAndSetAttribute(string name, string value, XmlNode parent){
		XmlAttribute field = doc.CreateAttribute(name, docNamespace);
		field.Value = value;
		parent.Attributes.Append(field);
	}
	#endregion

	#region Append Element
	/// <summary>

	/// Creates an element with the given name and value. Appends Element to the given parent.

	/// </summary>

	/// <param name="name"></param>

	/// <param name="value"></param>

	/// <param name="parent"></param>

	/// <returns></returns>

	public XmlNode AppendElement(string name, string value, XmlNode parent){
		return AppendElement(MakeAndSetElement(name,value),parent);
	}
	/// <summary>

	/// Creates an element with the given name and NO value. Appends Element to the given parent.

	/// </summary>

	/// <param name="name"></param>

	/// <param name="parent"></param>

	/// <returns></returns>

	public XmlNode AppendElement(string name, XmlNode parent){
		return AppendElement(MakeAndSetElement(name),parent);
	}
	/// <summary>

	/// Appends an element to the given parent.

	/// </summary>

	/// <param name="child"></param>

	/// <param name="parent"></param>

	/// <returns></returns>

	public XmlNode AppendElement(XmlNode child, XmlNode parent){
		parent.AppendChild(child);
		return child;
	}
	#endregion

	#region AppendElementToRoot
	/// <summary>

	/// Creates an element with the given name and NO value. Appends Element to the root.

	/// </summary>

	/// <param name="name"></param>

	/// <returns></returns>

	public XmlNode AppendElementToRoot(string name){
		return AppendElementToRoot(name,string.Empty);
	}
	/// <summary>

	/// Creates an element with the given name and value. Appends Element to the root.

	/// </summary>

	/// <param name="name"></param>

	/// <returns></returns>

	public XmlNode AppendElementToRoot(string name, string value){
		return AppendElementToRoot(MakeAndSetElement(name,value));
	}
	/// <summary>

	/// Appends an element to the root.

	/// </summary>

	/// <param name="child"></param>

	/// <param name="parent"></param>

	/// <returns></returns>

	public XmlNode AppendElementToRoot(XmlNode child){
		return AppendElement(child,this.rootNode);
	}
	#endregion

	#region Write XML
	/// <summary>

	/// Writes XML to string in Indented Format (good for debugging or printing to user)

	/// </summary>

	/// <returns></returns>

	public string WriteIndentedXML(){
		StringWriter strWriter = new StringWriter();
		XmlTextWriter xmlWriter = new XmlTextWriter(strWriter);
		xmlWriter.Formatting = Formatting.Indented;
		doc.WriteTo(xmlWriter);
		xmlWriter.Flush();
		strWriter.Flush();
		return strWriter.ToString();
	}
	/// <summary>

	/// Writes XML to string with no formatting (good for sending it to other programs)

	/// </summary>

	/// <returns></returns>

	public string WriteXML(){
		//System.Diagnostics.Trace.WriteLine(WriteIndentedXML());


		StringWriter strWriter = new StringWriter();
		XmlTextWriter xmlWriter = new XmlTextWriter(strWriter);
		xmlWriter.Formatting = Formatting.None;
		doc.WriteTo(xmlWriter);
		xmlWriter.Flush();
		strWriter.Flush();
		return strWriter.ToString();
	}
	#endregion
}
#endregion

#endregion

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

ColinBashBash



Location: United States United States

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 4 of 4 (Total in Forum: 4) (Refresh)FirstPrevNext
GeneralCode examplememberpeterc026916:04 3 Aug '06  
GeneralGive Some DemomemberSunil Manocha7:12 17 Jul '06  
Questionsingleselectnode -- errormemberseresha20:01 26 Mar '06  
GeneralWhat is it for?memberBoniolopez2:18 5 Oct '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 Mar 2006
Editor:
Copyright 2005 by ColinBashBash
Everything else Copyright © CodeProject, 1999-2008
Web15 | Advertise on the Code Project