Sign in to follow this  

[.net] Reading xml

This topic is 3664 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want to read an xml file which lots has nodes like this: <Add Key="I105" Source="FileNet - GetFileValues" Message="Value is obtained"/> I want to use the values corresponding to any keys in my code. Which is the best to way to do it? Reading xml to a dataset at the beginning and use select query against key is my thinking. But I am afraid it will impact the perforformance. Any suggestion for making my code better and cleaner? Thanks in advance.......

Share this post


Link to post
Share on other sites
You could create a helper class:


class Add
{
public string Key;
public string Source;
public string Message;
}


and then use the XmlSerializer to read the data in. Not very pretty, but easy enough to do.

hth,
CipherCraft

Share this post


Link to post
Share on other sites
Thanks for ur reply....
I am afraid I dont get you.
Actually I may need to use values of more than one keys at a single statement.

My XML is like this:

<MessageCodes>
<component>
<Add Key="I105" Source="FileNet - GetFileValues" Message="Value is obtained"/>
............

</component>
<component>
..........
</component>

.............


</MessageCodes>

If I deserialize xml , how can i get values using key?

Share this post


Link to post
Share on other sites
It really just depends on how you need to use the data. If you need to "tie" your data to some class, the helper/dataset isnt bad. But if you just need to parse and do some function, XmlDocument, or even XmlReader could do the job.

The good thing about XML is you have a ton of options. I would narrow your goals down and you might get more descriptive opinions.

Bourke

Share this post


Link to post
Share on other sites
I'd use XPath for this. Processing each "Add" element is then a simple operation:

XPathDocument doc = new XPathDocument("file.xml");
XPathNavigator nav = doc.CreateNavigator();

foreach(XPathNavigator addElemenet in nav.SelectChildren("/MessageCodes/component/Add[@key]"))
{
string key = addElement.GetAttribute("key");
string source = addElement.GetElement("source");
string message = addElement.GetElement("message");

// Do something with values.
}


You'd probably also want to modify the XPath query to filter on more than just the key attribute as well, if those other attributes are not actually optional. XPath can greatly ease the processing of XML in this fashion, as you don't have to nest a lot of loops or function calls performing hierachical traversal of the XML data manually. Although if you need to associate each key with its parent component, performing the query "/MessageCodes/component" may make more sense, and then nesting the query to select all "add" elements.

Share this post


Link to post
Share on other sites
Here's what I use, just input the filepath and the keyname and it returns the key value, you could either modify it to return an array of values or you can call it seperately for each value (Depends how fast you need the values.)

[CODE]
//Author: Dave Mandrella
using System;
using System.Xml;
using System.IO;
using System.Data;
using System.Collections;

#region LOAD XML KEY
public static string LoadXMLKey( string path, string key )
{
FileStream stream = null;

if( File.Exists( path ) )
{
try
{
// Get a DataSet object
DataSet data = new DataSet();

// Get a FileStream object.
stream = new FileStream(path,FileMode.Open,FileAccess.Read);
// Apply the ReadXml(fileStream method) to read the file
data.ReadXml(stream);

// Get a DataTable object from the first table of the DataSet
DataTable table = data.Tables[0];

// Display the values for each row
foreach (DataRow row in table.Rows)
{
if( key == row["name"].ToString() )
{
return row["value"].ToString();
}
}
}
catch ( Exception e )
{
//Information.ShowError( e.ToString() );
}
finally
{
if(stream != null)stream.Close();
}
}

return String.Empty;
}
#endregion
[/CODE]

[XML]
<?xml version="1.0" ?>

<config>
<key name="RegionFilePath">
<value>C:\regions.xml</value>
</key>
</config>
[/XML]

[EXAMPLE]
//Load RegionFilePath from config.xml
string exampleValue = LoadXMLKey("config.xml", "RegionFilePath");
[/EXAMPLE]

The whole goal here is modularity, I'm able to reuse this method in almost every project I create that needs to load a configuration file :)

Hope it helps,

-Dave Mandrella

PS: If you will be reading that file from multiple locations you will want to use a Mutex in the LoadXMLKey method.
[CODE]
using System.Threading;
Mutex mutex = new Mutex();
mutex.WaitOne();
//The Method's code
mutex.Release();
[/CODE]

[Edited by - thedavil on December 4, 2007 9:59:45 AM]

Share this post


Link to post
Share on other sites
Quote:
Original post by jpetrie
I'd use XPath for this. Processing each "Add" element is then a simple operation:

XPathDocument doc = new XPathDocument("file.xml");
XPathNavigator nav = doc.CreateNavigator();

foreach(XPathNavigator addElemenet in nav.SelectChildren("/MessageCodes/component/Add[@key]"))
{
string key = addElement.GetAttribute("key");
string source = addElement.GetElement("source");
string message = addElement.GetElement("message");

// Do something with values.
}


You'd probably also want to modify the XPath query to filter on more than just the key attribute as well, if those other attributes are not actually optional. XPath can greatly ease the processing of XML in this fashion, as you don't have to nest a lot of loops or function calls performing hierachical traversal of the XML data manually. Although if you need to associate each key with its parent component, performing the query "/MessageCodes/component" may make more sense, and then nesting the query to select all "add" elements.


Thanks for that tip!

Share this post


Link to post
Share on other sites

This topic is 3664 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this