473,382 Members | 1,784 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

XML Question

Hi all,

I'm playing around with an XML structured like this:

<root>
<subone>
<setting name = "xyz" value = "100" />
</subone>
<subtwo>
<list name = "abcde" value = "1000" />
<list name = "fghij" value = "2000" />
</subtwo>
</root>

I'm trying to figure out the most efficient way to read the attributes of
<subone> child nodes into one array and <subtwo> child nodes into another
array? Any ideas are welcome.

Thanks in advance,
Michael C., MCDBA
Nov 16 '05 #1
2 2212
"Michael C" <mi******@nospam.org> wrote in message news:t%**********************@news4.srv.hcvlny.cv. net...
I'm trying to figure out the most efficient way to read the attributes of
<subone> child nodes into one array and <subtwo> child nodes into another
array?


There are two factors that should be present in an efficient solution. First, use
XmlNameTable to get atomized strings for the "subone" and "subtwo" element
tag names, this will speed up comparisons by doing reference comparisons
instead of more expensive string comparisons. Second, use an XmlReader
to stream through the instance document.

The following class should support what you're trying to do, and it does so in
a very efficient manner.

- - - XmlAttributeCollector.cs
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Xml;

public class XmlAttributeCollector
{
private const int NOT_COLLECTING = -1;
private int currentArray;
private ArrayList[] subCollector;
private string[] atomizedTagNames;

// Creates an XmlAttributeCollector instance that will collect all attributes from the
// supplied tagnames (it also collects all attributes from ALL descendent elements
// of the supplied tagnames).
public XmlAttributeCollector( string[] tagNames)
{
this.currentArray = -1;
this.subCollector = new ArrayList[ tagNames.Length];
for( int i=0; i < this.subCollector.Length; ++i)
this.subCollector[ i] = new ArrayList( );
this.atomizedTagNames = tagNames;
}

// Adds all attribute values of the element node on which reader is currently positioned
// to the Collector array the Current Array index specifies.
private void AddAttributeToCollector( XmlReader reader)
{
Debug.Assert( ( currentArray != NOT_COLLECTING ), "Bad context: not inside one of the atomized tag names.");

if ( reader.MoveToFirstAttribute( ) ) do
{
this.subCollector[ this.currentArray].Add( reader.Value);
}
while ( reader.MoveToNextAttribute( ) );
}

// Atomizes the tag names this XmlAttributeCollector is looking for -- atomization
// applies per-XmlReader instance.
private void AtomizeTagNames( XmlReader reader)
{
XmlNameTable nt = reader.NameTable;
for( int i=0; i < atomizedTagNames.Length; ++i)
atomizedTagNames[ i] = nt.Add( atomizedTagNames[ i]);
}

// Changes CurrentArray index to a nonnegative integer when the tagName argument
// matches one of the atomizedTagNames this Collector is collecting for; or changes it
// to NOT_COLLECTING when type suggests I am leaving the scope of a tagName
// I'm collecting for.
private void UpdateCurrentArrayIndex( string tagName, XmlNodeType type)
{
int i = atomizedTagNames.Length;
while ( ( --i > NOT_COLLECTING ) && ( tagName != atomizedTagNames[ i] ) )
;
if ( i > NOT_COLLECTING )
this.currentArray = ( XmlNodeType.EndElement == type ) ? NOT_COLLECTING : i;
}

// Collects all XML attributes appearing in the tag names this XmlAttributeCollector
// was created to collect attribute values for, and any descendants, into one or more
// arrays. If run on more than one XmlReader, attribute values from tag names of
// interest can be accumulated from multiple XML documents.
public void CollectXmlAttributes( XmlReader reader)
{
if ( null == reader )
throw new ArgumentNullException( "reader");

AtomizeTagNames( reader);
while ( reader.Read( ) )
{
UpdateCurrentArrayIndex( reader.LocalName, reader.NodeType);
if ( reader.NodeType == XmlNodeType.Element )
if ( this.currentArray != NOT_COLLECTING )
AddAttributeToCollector( reader);
}
}

// Dumps the attribute values collected for the tag names of interest to
// any TextWriter.
public void DumpContents( TextWriter sink)
{
if ( null == sink )
throw new ArgumentNullException( "sink");
for ( int i = 0; i < this.atomizedTagNames.Length; ++i)
{
sink.WriteLine( "---- attribute values under <{0}> descendants ----", this.atomizedTagNames[ i]);
for ( int j = 0, jMax = this.subCollector[ i].Count; j < jMax; ++j)
sink.WriteLine( this.subCollector[ i][ j].ToString( ) );
}
sink.WriteLine( "---- ------- ----");
}

// If any attribute values have been collected, then this method resets all of the
// collectors to their initial empty state.
public void ResetContents( )
{
for( int i = 0; i < this.atomizedTagNames.Length; ++i)
this.subCollector[ i].Clear( );
}
}
- - -

In your case, you might use this class with the following few lines of code:

XmlTextReader reader = new XmlTextReader( "root.xml");
XmlAttributeCollector collector = new XmlAttributeCollector( new string[] { "subone", "subtwo"} );
collector.CollectXmlAttributes( reader);
reader.Close( );
collector.DumpContents( Console.Out);

You'd pass the element names you're interested in collecting attribute values
from (both on them, and all of their descendants) and these tag names would
be atomized as soon as the XmlAttributeCollector receives an XmlReader
(the call to CollectXmlAttributes( )) because it requires the XmlReader's
NameTable to do so.

One cautionary note on choosing between XmlReader and XmlDocument for
efficiency. Frequently developers need to do more than one thing (like the
accumulation of attribute values) with an XML document. XmlReader is the
most expeditious way to get through the document in a forward-only, firehose
sense. Simple tasks like accumulating the attribute values under a select
number of elements can be very easily done. On the other hand, if you
require multiple tasks to be performed, and then make multiple passes
through the document with an XmlReader, the pendulum often swings
towards using an XmlDocument instead. After overcoming the hurdle
of reading the entire document and parsing the document into a node tree
(it must complete these steps before you can do any processing), the
XmlDocument may become a better candidate for consideration.
Derek Harmon
Nov 16 '05 #2
Thanks Derek,

I'm going to try your method.

Michael C., MCDBA

"Derek Harmon" <lo*******@msn.com> wrote in message
news:us**************@TK2MSFTNGP09.phx.gbl...
"Michael C" <mi******@nospam.org> wrote in message news:t%**********************@news4.srv.hcvlny.cv. net...
I'm trying to figure out the most efficient way to read the attributes of <subone> child nodes into one array and <subtwo> child nodes into another array?


There are two factors that should be present in an efficient solution.

First, use XmlNameTable to get atomized strings for the "subone" and "subtwo" element
tag names, this will speed up comparisons by doing reference comparisons
instead of more expensive string comparisons. Second, use an XmlReader
to stream through the instance document.

The following class should support what you're trying to do, and it does so in a very efficient manner.

- - - XmlAttributeCollector.cs
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Xml;

public class XmlAttributeCollector
{
private const int NOT_COLLECTING = -1;
private int currentArray;
private ArrayList[] subCollector;
private string[] atomizedTagNames;

// Creates an XmlAttributeCollector instance that will collect all attributes from the // supplied tagnames (it also collects all attributes from ALL descendent elements // of the supplied tagnames).
public XmlAttributeCollector( string[] tagNames)
{
this.currentArray = -1;
this.subCollector = new ArrayList[ tagNames.Length];
for( int i=0; i < this.subCollector.Length; ++i)
this.subCollector[ i] = new ArrayList( );
this.atomizedTagNames = tagNames;
}

// Adds all attribute values of the element node on which reader is currently positioned // to the Collector array the Current Array index specifies.
private void AddAttributeToCollector( XmlReader reader)
{
Debug.Assert( ( currentArray != NOT_COLLECTING ), "Bad context: not inside one of the atomized tag names.");
if ( reader.MoveToFirstAttribute( ) ) do
{
this.subCollector[ this.currentArray].Add( reader.Value);
}
while ( reader.MoveToNextAttribute( ) );
}

// Atomizes the tag names this XmlAttributeCollector is looking for -- atomization // applies per-XmlReader instance.
private void AtomizeTagNames( XmlReader reader)
{
XmlNameTable nt = reader.NameTable;
for( int i=0; i < atomizedTagNames.Length; ++i)
atomizedTagNames[ i] = nt.Add( atomizedTagNames[ i]);
}

// Changes CurrentArray index to a nonnegative integer when the tagName argument // matches one of the atomizedTagNames this Collector is collecting for; or changes it // to NOT_COLLECTING when type suggests I am leaving the scope of a tagName // I'm collecting for.
private void UpdateCurrentArrayIndex( string tagName, XmlNodeType type) {
int i = atomizedTagNames.Length;
while ( ( --i > NOT_COLLECTING ) && ( tagName != atomizedTagNames[ i] ) ) ;
if ( i > NOT_COLLECTING )
this.currentArray = ( XmlNodeType.EndElement == type ) ? NOT_COLLECTING : i; }

// Collects all XML attributes appearing in the tag names this XmlAttributeCollector // was created to collect attribute values for, and any descendants, into one or more // arrays. If run on more than one XmlReader, attribute values from tag names of // interest can be accumulated from multiple XML documents.
public void CollectXmlAttributes( XmlReader reader)
{
if ( null == reader )
throw new ArgumentNullException( "reader");

AtomizeTagNames( reader);
while ( reader.Read( ) )
{
UpdateCurrentArrayIndex( reader.LocalName, reader.NodeType);
if ( reader.NodeType == XmlNodeType.Element )
if ( this.currentArray != NOT_COLLECTING )
AddAttributeToCollector( reader);
}
}

// Dumps the attribute values collected for the tag names of interest to // any TextWriter.
public void DumpContents( TextWriter sink)
{
if ( null == sink )
throw new ArgumentNullException( "sink");
for ( int i = 0; i < this.atomizedTagNames.Length; ++i)
{
sink.WriteLine( "---- attribute values under <{0}> descendants ----", this.atomizedTagNames[ i]); for ( int j = 0, jMax = this.subCollector[ i].Count; j < jMax; ++j) sink.WriteLine( this.subCollector[ i][ j].ToString( ) );
}
sink.WriteLine( "---- ------- ----");
}

// If any attribute values have been collected, then this method resets all of the // collectors to their initial empty state.
public void ResetContents( )
{
for( int i = 0; i < this.atomizedTagNames.Length; ++i)
this.subCollector[ i].Clear( );
}
}
- - -

In your case, you might use this class with the following few lines of code:
XmlTextReader reader = new XmlTextReader( "root.xml");
XmlAttributeCollector collector = new XmlAttributeCollector( new string[] { "subone", "subtwo"} ); collector.CollectXmlAttributes( reader);
reader.Close( );
collector.DumpContents( Console.Out);

You'd pass the element names you're interested in collecting attribute values from (both on them, and all of their descendants) and these tag names would be atomized as soon as the XmlAttributeCollector receives an XmlReader
(the call to CollectXmlAttributes( )) because it requires the XmlReader's
NameTable to do so.

One cautionary note on choosing between XmlReader and XmlDocument for
efficiency. Frequently developers need to do more than one thing (like the accumulation of attribute values) with an XML document. XmlReader is the
most expeditious way to get through the document in a forward-only, firehose sense. Simple tasks like accumulating the attribute values under a select
number of elements can be very easily done. On the other hand, if you
require multiple tasks to be performed, and then make multiple passes
through the document with an XmlReader, the pendulum often swings
towards using an XmlDocument instead. After overcoming the hurdle
of reading the entire document and parsing the document into a node tree
(it must complete these steps before you can do any processing), the
XmlDocument may become a better candidate for consideration.
Derek Harmon

Nov 16 '05 #3

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

Similar topics

1
by: Mohammed Mazid | last post by:
Can anyone please help me on how to move to the next and previous question? Here is a snippet of my code: Private Sub cmdNext_Click() End Sub Private Sub cmdPrevious_Click() showrecord
3
by: Stevey | last post by:
I have the following XML file... <?xml version="1.0"?> <animals> <animal> <name>Tiger</name> <questions> <question index="0">true</question> <question index="1">true</question> </questions>
7
by: nospam | last post by:
Ok, 3rd or is it the 4th time I have asked this question on Partial Types, so, since it seems to me that Partial Types is still in the design or development stages at Microsoft, I am going to ask...
3
by: Ekqvist Marko | last post by:
Hi, I have one Access database table including questions and answers. Now I need to give answer id automatically to questionID column. But I don't know how it is best (fastest) to do? table...
10
by: glenn | last post by:
I am use to programming in php and the way session and post vars are past from fields on one page through to the post page automatically where I can get to their values easily to write to a...
10
by: Rider | last post by:
Hi, simple(?) question about asp.net configuration.. I've installed ASP.NET 2.0 QuickStart Sample successfully. But, When I'm first start application the follow message shown. ========= Server...
53
by: Jeff | last post by:
In the function below, can size ever be 0 (zero)? char *clc_strdup(const char * CLC_RESTRICT s) { size_t size; char *p; clc_assert_not_null(clc_strdup, s); size = strlen(s) + 1;
56
by: spibou | last post by:
In the statement "a *= expression" is expression assumed to be parenthesized ? For example if I write "a *= b+c" is this the same as "a = a * (b+c)" or "a = a * b+c" ?
2
by: Allan Ebdrup | last post by:
Hi, I'm trying to render a Matrix question in my ASP.Net 2.0 page, A matrix question is a question where you have several options that can all be rated according to several possible ratings (from...
3
by: Zhang Weiwu | last post by:
Hello! I wrote this: ..required-question p:after { content: "*"; } Corresponding HTML: <div class="required-question"><p>Question Text</p><input /></div> <div...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.