473,809 Members | 2,931 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2263
"Michael C" <mi******@nospa m.org> wrote in message news:t%******** **************@ news4.srv.hcvln y.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.

- - - XmlAttributeCol lector.cs
using System;
using System.Collecti ons;
using System.Diagnost ics;
using System.IO;
using System.Xml;

public class XmlAttributeCol lector
{
private const int NOT_COLLECTING = -1;
private int currentArray;
private ArrayList[] subCollector;
private string[] atomizedTagName s;

// Creates an XmlAttributeCol lector instance that will collect all attributes from the
// supplied tagnames (it also collects all attributes from ALL descendent elements
// of the supplied tagnames).
public XmlAttributeCol lector( string[] tagNames)
{
this.currentArr ay = -1;
this.subCollect or = new ArrayList[ tagNames.Length];
for( int i=0; i < this.subCollect or.Length; ++i)
this.subCollect or[ i] = new ArrayList( );
this.atomizedTa gNames = 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 AddAttributeToC ollector( XmlReader reader)
{
Debug.Assert( ( currentArray != NOT_COLLECTING ), "Bad context: not inside one of the atomized tag names.");

if ( reader.MoveToFi rstAttribute( ) ) do
{
this.subCollect or[ this.currentArr ay].Add( reader.Value);
}
while ( reader.MoveToNe xtAttribute( ) );
}

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

// Changes CurrentArray index to a nonnegative integer when the tagName argument
// matches one of the atomizedTagName s 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 UpdateCurrentAr rayIndex( string tagName, XmlNodeType type)
{
int i = atomizedTagName s.Length;
while ( ( --i > NOT_COLLECTING ) && ( tagName != atomizedTagName s[ i] ) )
;
if ( i > NOT_COLLECTING )
this.currentArr ay = ( XmlNodeType.End Element == type ) ? NOT_COLLECTING : i;
}

// Collects all XML attributes appearing in the tag names this XmlAttributeCol lector
// 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 CollectXmlAttri butes( XmlReader reader)
{
if ( null == reader )
throw new ArgumentNullExc eption( "reader");

AtomizeTagNames ( reader);
while ( reader.Read( ) )
{
UpdateCurrentAr rayIndex( reader.LocalNam e, reader.NodeType );
if ( reader.NodeType == XmlNodeType.Ele ment )
if ( this.currentArr ay != NOT_COLLECTING )
AddAttributeToC ollector( 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 ArgumentNullExc eption( "sink");
for ( int i = 0; i < this.atomizedTa gNames.Length; ++i)
{
sink.WriteLine( "---- attribute values under <{0}> descendants ----", this.atomizedTa gNames[ i]);
for ( int j = 0, jMax = this.subCollect or[ i].Count; j < jMax; ++j)
sink.WriteLine( this.subCollect or[ 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.atomizedTa gNames.Length; ++i)
this.subCollect or[ i].Clear( );
}
}
- - -

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

XmlTextReader reader = new XmlTextReader( "root.xml") ;
XmlAttributeCol lector collector = new XmlAttributeCol lector( new string[] { "subone", "subtwo"} );
collector.Colle ctXmlAttributes ( reader);
reader.Close( );
collector.DumpC ontents( 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 XmlAttributeCol lector receives an XmlReader
(the call to CollectXmlAttri butes( )) 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******** ******@TK2MSFTN GP09.phx.gbl...
"Michael C" <mi******@nospa m.org> wrote in message news:t%******** **************@ news4.srv.hcvln y.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.

- - - XmlAttributeCol lector.cs
using System;
using System.Collecti ons;
using System.Diagnost ics;
using System.IO;
using System.Xml;

public class XmlAttributeCol lector
{
private const int NOT_COLLECTING = -1;
private int currentArray;
private ArrayList[] subCollector;
private string[] atomizedTagName s;

// Creates an XmlAttributeCol lector instance that will collect all attributes from the // supplied tagnames (it also collects all attributes from ALL descendent elements // of the supplied tagnames).
public XmlAttributeCol lector( string[] tagNames)
{
this.currentArr ay = -1;
this.subCollect or = new ArrayList[ tagNames.Length];
for( int i=0; i < this.subCollect or.Length; ++i)
this.subCollect or[ i] = new ArrayList( );
this.atomizedTa gNames = 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 AddAttributeToC ollector( XmlReader reader)
{
Debug.Assert( ( currentArray != NOT_COLLECTING ), "Bad context: not inside one of the atomized tag names.");
if ( reader.MoveToFi rstAttribute( ) ) do
{
this.subCollect or[ this.currentArr ay].Add( reader.Value);
}
while ( reader.MoveToNe xtAttribute( ) );
}

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

// Changes CurrentArray index to a nonnegative integer when the tagName argument // matches one of the atomizedTagName s 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 UpdateCurrentAr rayIndex( string tagName, XmlNodeType type) {
int i = atomizedTagName s.Length;
while ( ( --i > NOT_COLLECTING ) && ( tagName != atomizedTagName s[ i] ) ) ;
if ( i > NOT_COLLECTING )
this.currentArr ay = ( XmlNodeType.End Element == type ) ? NOT_COLLECTING : i; }

// Collects all XML attributes appearing in the tag names this XmlAttributeCol lector // 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 CollectXmlAttri butes( XmlReader reader)
{
if ( null == reader )
throw new ArgumentNullExc eption( "reader");

AtomizeTagNames ( reader);
while ( reader.Read( ) )
{
UpdateCurrentAr rayIndex( reader.LocalNam e, reader.NodeType );
if ( reader.NodeType == XmlNodeType.Ele ment )
if ( this.currentArr ay != NOT_COLLECTING )
AddAttributeToC ollector( 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 ArgumentNullExc eption( "sink");
for ( int i = 0; i < this.atomizedTa gNames.Length; ++i)
{
sink.WriteLine( "---- attribute values under <{0}> descendants ----", this.atomizedTa gNames[ i]); for ( int j = 0, jMax = this.subCollect or[ i].Count; j < jMax; ++j) sink.WriteLine( this.subCollect or[ 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.atomizedTa gNames.Length; ++i)
this.subCollect or[ i].Clear( );
}
}
- - -

In your case, you might use this class with the following few lines of code:
XmlTextReader reader = new XmlTextReader( "root.xml") ;
XmlAttributeCol lector collector = new XmlAttributeCol lector( new string[] { "subone", "subtwo"} ); collector.Colle ctXmlAttributes ( reader);
reader.Close( );
collector.DumpC ontents( 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 XmlAttributeCol lector receives an XmlReader
(the call to CollectXmlAttri butes( )) 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
3102
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
5045
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
2668
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 it differently. FOUR QUESTIONS: The background: I got three (3) files
3
3096
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 before rowID answID qryrow questionID datafield 1591 12 06e 06e 06e question 1593 12 06f 06f 06f question 1594 12 answer to the question 06f
10
3444
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 database or continue to process on to the next page. I am now trying to learn ASP to see if we can replace some of our applications that were written in php with an ASP alternative. However, after doing many searches on google and reading a couple...
10
3745
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 Error in '/QuickStartv20' Application. -------------------------------------------------------------------------------- Configuration Error Description: An error occurred during the processing of a configuration file
53
4100
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
4812
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
4288
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 less to more for example). I have a question object that has two properties that contain the collections Options and Ratings. now I want this kind of layout: --- Rating1 Rating2 Rating3 Option 1 () () ...
3
2559
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 class="not-required-question"><p>Question Text</p><input /></div>
0
9721
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
10376
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
10114
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
9198
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...
1
7651
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6880
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
5686
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3860
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3011
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.