473,785 Members | 2,987 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help Creating XmlNode / XmlAttribute Elegantly

I am creating a configuration class to read / write a standard configuration file.

<?xml version="1.0" encoding="utf-8"?>
<configuratio n>
<appSettings>
<add key="Connection String" value="server=( local);" />
</appSettings>
</configuration>

I am using a XmlDocument for my base implementation.

I am looking to see if there is a better way to add a new node / attribute than using
XmlDocument.Inn erXml. I would consider this to be a hack but couldn't really see another
way of doing this without defining namespaces and the like.

I have included the full file below and the lines that I am wondering about are lines: 79, 227, and 266

Thanks,
Dave
=============== =============== =====

using System;
using System.Xml;
using System.Text;

namespace Storage.Utility .Configuration
{
/// <summary>
/// Class for Reading / Writing Configuration Options
/// </summary>
public class Configuration
{
#region Data Members

private XmlDocument xmlDoc = null;
private XmlElement root = null;
private XmlNode node = null;

private string filename = null;
private string queryString = null;

#endregion

#region Constructor

public Configuration(s tring configFileName)
{
filename = configFileName;
}

#endregion

#region Methods

#region Miscellaneous

/// <summary>
/// Initialize the Configuration Class
/// </summary>
private void Initialize()
{
LoadConfigurati on();
}

#endregion

#region File Access

/// <summary>
/// Reload the Configuration File
/// </summary>
public void ReloadConfigura tion()
{
LoadConfigurati on();
}
/// <summary>
/// Save the Configuration File
/// </summary>
public void Save()
{
SaveConfigurati on();
}
/// <summary>
/// Load the Configuration File
/// </summary>
private void LoadConfigurati on()
{
try
{
xmlDoc = new XmlDocument();
xmlDoc.Load(fil ename);
}
catch (Exception)
{
// Create Configuration File
xmlDoc.InnerXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><configura tion></configuration>" ;
}
finally
{
root = xmlDoc.Document Element;
}
}
/// <summary>
/// Save the Configuration File
/// </summary>
private void SaveConfigurati on()
{
try
{
xmlDoc.Save(fil ename);
}
catch (Exception ex)
{
// Can't do anything
throw (ex);
}
}

#endregion

#region Retrieve Values

/// <summary>
/// Get the Value of the Key
/// </summary>
/// <param name="section"> </param>
/// <param name="key"></param>
/// <returns></returns>
public string GetValue(string section, string key)
{
try
{
// Find the Node
node = GetValueNode(se ction, key);
if (node != null)
{
// Retrieve Value
XmlNode valueNode = node.Attributes .GetNamedItem(" value");
return (valueNode.Valu e);
}
}
catch (Exception)
{
// Nothing to do
}

// Error Occurred
return (null);
}
/// <summary>
/// Find the Node that the Key belongs to
/// </summary>
/// <param name="section"> </param>
/// <param name="key"></param>
/// <returns></returns>
private XmlNode GetValueNode(st ring section, string key)
{
try
{
// XML Search Path
queryString = "/configuration/" + section + "/add[@key=\"" + key + "\"]";

// Look from the Root of the Document
return (root.SelectSin gleNode(querySt ring));
}
catch (Exception)
{
// Nothing to do
}

// Error Occurred
return (null);
}

#endregion

#region Store Values

/// <summary>
/// Store Key / Value in Configuration File
/// </summary>
/// <param name="section"> </param>
/// <param name="key"></param>
/// <param name="keyValue" ></param>
/// <returns></returns>
public bool StoreValue(stri ng section, string key, string keyValue)
{
try
{
// Find Node if it exists
node = GetValueNode(se ction, key);
if (node != null)
{
// Update Value
node = node.Attributes .GetNamedItem(" value");
node.Value = keyValue;
return (true);
}

// Node Doesn't Exist -> Get/Create Section -> Add Key / Value
if (GetSection(sec tion) == true)
return (CreateValueNod e(section, key, keyValue));
}
catch (Exception)
{
// Nothing to do
}

// Error Occurred
return (false);
}

#endregion

#region Create Nodes

/// <summary>
/// Create New Key / Value Entry
/// </summary>
/// <param name="section"> </param>
/// <param name="key"></param>
/// <param name="keyValue" ></param>
/// <returns></returns>
private bool CreateValueNode (string section, string key, string keyValue)
{
try
{
// Get Section
queryString = "/configuration/" + section;
node = root.SelectSing leNode(queryStr ing);

// Node Must Exist
if (node != null)
{
// Create and Add New Key / Value Entry
StringBuilder sb = new StringBuilder(5 00);
sb.Append("<add key=\""); sb.Append(key); sb.Append("\" ");
sb.Append("valu e=\""); sb.Append(keyVa lue); sb.Append("\" />");

node.InnerXml += sb.ToString();
return (true);
}
}
catch (Exception)
{
// Nothing to do
}

// Error Occurred
return (false);
}
/// <summary>
/// Get / Create a New Configuration Section
/// </summary>
/// <param name="section"> </param>
/// <returns></returns>
private bool GetSection(stri ng section)
{
try
{
// Does the Section Exist
queryString = "/configuration/" + section;
node = root.SelectSing leNode(queryStr ing);
if (node != null)
return (true);

// Get the Configuration Node
queryString = "/configuration";
node = root.SelectSing leNode(queryStr ing);
if (node != null)
{
// Create a New Section
StringBuilder sb = new StringBuilder(1 000);
sb.Append("<"); sb.Append(secti on); sb.Append(">");
sb.Append("</"); sb.Append(secti on); sb.Append(">");

node.InnerXml += sb.ToString();
return (true);
}
}
catch (Exception)
{
// Nothing to do
}

// Error Occurred
return (false);
}
#endregion

#endregion

} // Class
}

Nov 12 '05 #1
2 10389
"David Elliott" <We*****@newsgr oups.nospam> wrote in message news:2b******** *************** *********@4ax.c om...
I am looking to see if there is a better way to add a
new node / attribute than using XmlDocument.Inn erXml. : : but couldn't really see another way of doing this without
defining namespaces and the like.
The example XML you've given doesn't contain any namespaces,
so why should you define one?

Have a look at the CreateElement() and CreateAttribute ()
methods of XmlDocument, and then AppendChild() on XmlNode
(and remember that XmlDocument is an XmlNode, so it also
allows you to AppendChild() nodes to it).
the lines that I am wondering about are lines: 79, 227,
and 266

79: xmlDoc.InnerXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><configura tion></configuration>" ;

If you set UTF-8 Encoding on an I/O Stream wrapped by an
XmlTextWriter (or TextWriter), this XML declaration will
be emitted for you automatically.

Here's how you'd create a custom XmlDeclaration for the
XmlDocument (note that if you do Save this XML to a
TextWriter-based class, its Encoding takes precedence).

XmlDeclaration xmlDecl = xmlDoc.CreateXm lDeclaration("1 .0", "utf-8", "");

Then you'd want to create your <configuratio n> element.

XmlElement eRoot = xmlDoc.CreateEl ement( "configuration" );

Finally, add the root element to XmlDocument and insert
the XmlDeclaration before it,

xmlDoc.AppendCh ild( eRoot);
xmlDoc.InsertBe fore( xmlDecl, eRoot);
: :
223: StringBuilder sb = new StringBuilder(5 00);
224: sb.Append("<add key=\""); sb.Append(key); sb.Append("\" ");
225: sb.Append("valu e=\""); sb.Append(keyVa lue); sb.Append("\" />");
226:
227: node.InnerXml += sb.ToString();

XmlElement eAdd = xmlDoc.CreateEl ement( "add");
eAdd.SetAttribu te( "key", key);
eAdd.SetAttribu te( "value", keyValue);
node.AppendChil d( eAdd);
: :
264: sb.Append("</"); sb.Append(secti on); sb.Append(">");
265:
266: node.InnerXml += sb.ToString();

Your example code never gives a value to the argument,
section, but from your example XML I'll guess it's
<appSettings> (although I don't see where you have
inserted the child node between the start and end
elements).
XmlElement eAppSettings = xmlDoc.CreateEl ement( "appSetting s");
eAppSettings.Ap pendChild( eAdd);
eRoot.AppendChi ld( eAppSettings);
These three statements essentially tie together the
entire configuration document's XML nodes.

It looks like you own (because you want to own?) the
entire configuration file, but I'll also point out that
in the .NET Framework's System.Configur ation namespace
are classes automatically supporting this configuration
schema to read a config file from "application.ex e.config"
or "web.config ".

Using the built-in configuration file support allows you
to create the element,

<add name="key" value="keyValue " />

in a single statement like this,

ConfigurationSe ttings.AppSetti ngs[ key] = keyValue;

with the default NameValueSectio nHandler.

Derek Harmon
Nov 12 '05 #2
Thanks,
Dave

"Derek Harmon" wrote:
"David Elliott" <We*****@newsgr oups.nospam> wrote in message news:2b******** *************** *********@4ax.c om...
I am looking to see if there is a better way to add a
new node / attribute than using XmlDocument.Inn erXml.

: :
but couldn't really see another way of doing this without
defining namespaces and the like.


The example XML you've given doesn't contain any namespaces,
so why should you define one?

Have a look at the CreateElement() and CreateAttribute ()
methods of XmlDocument, and then AppendChild() on XmlNode
(and remember that XmlDocument is an XmlNode, so it also
allows you to AppendChild() nodes to it).
the lines that I am wondering about are lines: 79, 227,
and 266

79: xmlDoc.InnerXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><configura tion></configuration>" ;

If you set UTF-8 Encoding on an I/O Stream wrapped by an
XmlTextWriter (or TextWriter), this XML declaration will
be emitted for you automatically.

Here's how you'd create a custom XmlDeclaration for the
XmlDocument (note that if you do Save this XML to a
TextWriter-based class, its Encoding takes precedence).

XmlDeclaration xmlDecl = xmlDoc.CreateXm lDeclaration("1 .0", "utf-8", "");

Then you'd want to create your <configuratio n> element.

XmlElement eRoot = xmlDoc.CreateEl ement( "configuration" );

Finally, add the root element to XmlDocument and insert
the XmlDeclaration before it,

xmlDoc.AppendCh ild( eRoot);
xmlDoc.InsertBe fore( xmlDecl, eRoot);
: :
223: StringBuilder sb = new StringBuilder(5 00);
224: sb.Append("<add key=\""); sb.Append(key); sb.Append("\" ");
225: sb.Append("valu e=\""); sb.Append(keyVa lue); sb.Append("\" />");
226:
227: node.InnerXml += sb.ToString();

XmlElement eAdd = xmlDoc.CreateEl ement( "add");
eAdd.SetAttribu te( "key", key);
eAdd.SetAttribu te( "value", keyValue);
node.AppendChil d( eAdd);
: :
264: sb.Append("</"); sb.Append(secti on); sb.Append(">");
265:
266: node.InnerXml += sb.ToString();

Your example code never gives a value to the argument,
section, but from your example XML I'll guess it's
<appSettings> (although I don't see where you have
inserted the child node between the start and end
elements).
XmlElement eAppSettings = xmlDoc.CreateEl ement( "appSetting s");
eAppSettings.Ap pendChild( eAdd);
eRoot.AppendChi ld( eAppSettings);
These three statements essentially tie together the
entire configuration document's XML nodes.

It looks like you own (because you want to own?) the
entire configuration file, but I'll also point out that
in the .NET Framework's System.Configur ation namespace
are classes automatically supporting this configuration
schema to read a config file from "application.ex e.config"
or "web.config ".

Using the built-in configuration file support allows you
to create the element,

<add name="key" value="keyValue " />

in a single statement like this,

ConfigurationSe ttings.AppSetti ngs[ key] = keyValue;

with the default NameValueSectio nHandler.

Derek Harmon

Nov 12 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
14975
by: Anita C | last post by:
I have the foll. code to update the value of an attribute: xmlDocument.Load("abc.xml"); XmlAttribute xmlAttrib = xmlDocument.SelectSingleNode(root/web/theme/@desc); xmlAttrib.Value = ddDes.SelectedItem.ToString(); xmlDocument.Save("abc.xml"); However, I get the foll. error: Cannot implicitly convert type 'System.Xml.XmlNode' to 'System.Xml.XmlAttribute'
0
1228
by: Robert Bruce | last post by:
Hello, I'm trying to round-trip some XML out of Adobe InDesign, through my application and then back into InDesign. Tables in InDesign are created using a specific namespace like this: <Table TABLE_TYPE="table05" xmlns:aid="http://ns.adobe.com/AdobeInDesign/4.0/" aid:table="table" aid:trows="7" aid:tcols="2">
1
4128
by: BJ Allmon | last post by:
I'm new to the .NET community. My name is BJ and I've been developing web applications for years now. I'm very new to .NET and could use some assistance. I don't think I'm asking for very much here. This should be very common but I haven't been able to find any concrete examples. I'm creating a Windows Forms client/server application. It's for sales staff and the client piece needs to store to xml (preferrably). I know that windows...
0
1305
by: mortb | last post by:
My problem is with a XML file that resides on my windows 2003 web server. I have this user control which I include on every page in my applicaiton. The control makes it possible for the users to leave feedback when using the page. The feedback is written to a XML file which I have put in a folder "C:/Save/". I've set the access rights on this folder so that the "IUSR_MachineName" has full rights on this folder and it's children. The...
2
1195
by: Paul | last post by:
Is there a way to test if an XmlNode represents an enum?
3
27327
by: Andy | last post by:
Hello Guys: What am I doing wrong with this code? I can't seem to get it to simply add an attribute to my node. The node already exists. I am simply opening the XMLDocument and creating one attribute to the document. I am not creating the document new XmlNamespaceManager xnsm = new XmlNamespaceManager(xmlFile.NameTable); xnsm.AddNamespace("a", "http://www.icsm.com/icsmxml");
5
4739
by: MaxMax | last post by:
If I have an XmlNode/XmlAttribute and I want to convert its value to a "native" c# type (for example boolean), how should I do? I can't (for example) simply use Boolean.TryParse, because Xml Boolean considers 0 and 1 to be "good" values for a boolean type. --- bye
7
1560
by: Peter Bradley | last post by:
Hi, First of all, a confession. This is a cross post from the microsoft.public.dotnet.general list. I posted there not realising that this list existed. Apologies to those who read both lists. I'll do my best to prevent two separate conversations developing. I'm trying to create an XML Document. This is what I want to end up with:
4
13630
by: CSharper | last post by:
I am reading an XmlFile using XmlDocument and traverse through the XmlNode, as I read I need to append an attribute to the XmlNode on some conditions. I tried xmlNode.Attributes.Append() It takes only XmlAttribute and in this when I create a new XmlAttribute, it doesn't allow me to set the name and value as the name is only the readonly value. How can I achive this?
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10151
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8973
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6740
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.