Click here to Skip to main content
Click here to Skip to main content
Articles » Languages » XML » Utilities » Revisions
 
Go to top

Quick XML Read and Write Adapters for C#

, 9 Mar 2006
Rate this:
Please Sign up or sign in to vote.
For cleaner code. Easy to add methods as needed.

Introduction

This article provides some simple adapters to help separate XML documents from the business logic. The reader allows you to grab a child's value or a child's attribute. It also allows you to check to see if a child exists. It lets you grab a node subset --> basically, if you sent it a "child list", it would return a NodeList of the grand children:

<currNode>
  <child1/>
  <child2/>
  <childList>
     <grandchild>
        <property1/>
        <property2/>
     </grandchild>
     <grandchild>
        <property1/>
        <property2/>
     </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.) It also allows for appending those nodes. Lots of overloaded methods are available. The writer also allows for printing the document.

Add and change the code 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

History

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ColinBashBash
Software Developer
United States United States
likes boardgames, computer games, and enjoys his .net programming job.

Comments and Discussions


| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 9 Mar 2006
Article Copyright 2005 by ColinBashBash
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid