473,386 Members | 1,758 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,386 software developers and data experts.

Confused on reading attributes of an XML element.

Hi,

I have an xml file with structured like this:

<?xml version="1.0" encoding="UTF-8"?>
<Soldiers>
<Soldier name="Billy Smith" rank="Private" serial="34" />

(a bunch more soldiers)

</Soldiers>

In my program, I have a struct:

public struct soldierStruct
{
public string name;
public string rank;
public string serial;
}

I would like to make a loop that reads however many XML-soldiers there
are into an ArrayList of struct-soldiers. I can come up with the
framework for it, it's just the reading attributes part that I don't
understand how to do. Can anyone help?

Thanks for any suggestions,

cdj

===============
Framework:

public ArrayList GetSoldiers()
{
ArrayList soldiers= new ArrayList();
soldiers.clear();

XmlTextReader reader = new XmlTextReader(path + filename);
reader.Read();
while (reader.Read())
{
soldierStruct sol;

//Stuff here to make sure the reader is
where
//it's supposed to be?????

sol.name = ????? //Need attribute help
somewhere around here
sol.rank = ??????
sol.serial = ??????

soldiers.add(sol)
}

return soldiers;
}

Nov 30 '06 #1
4 1954


"sherifffruitfly" <sh*************@gmail.comwrote in message
news:11**********************@l39g2000cwd.googlegr oups.com...
Hi,

I have an xml file with structured like this:

<?xml version="1.0" encoding="UTF-8"?>
<Soldiers>
<Soldier name="Billy Smith" rank="Private" serial="34" />

(a bunch more soldiers)

</Soldiers>

In my program, I have a struct:

public struct soldierStruct
{
public string name;
public string rank;
public string serial;
}

I would like to make a loop that reads however many XML-soldiers there
are into an ArrayList of struct-soldiers. I can come up with the
framework for it, it's just the reading attributes part that I don't
understand how to do. Can anyone help?

Thanks for any suggestions,

cdj

===============
Framework:

public ArrayList GetSoldiers()
{
ArrayList soldiers= new ArrayList();
soldiers.clear();

XmlTextReader reader = new XmlTextReader(path + filename);
reader.Read();
while (reader.Read())
{
soldierStruct sol;

//Stuff here to make sure the reader is
where
//it's supposed to be?????

sol.name = ????? //Need attribute help
somewhere around here
sol.rank = ??????
sol.serial = ??????

soldiers.add(sol)
}

return soldiers;
}
I know this may not help you, but hey, it just might be of some use to you.
You can try creating a typed dataset and using it's methods to save to an
xml string/file or load from an xml string/file. All the reading/parsing of
the xml file is internal to the dataset and you get your "name", "rank",
"serial", etc properties because it is a typed dataset.

Just thought you may like to try a slightly alternate but easier approach :)

HTH,
Mythran
Nov 30 '06 #2
XmlReader can be hard. Once you know your node is a Soldier (possibly using
ReadToFollowing) you
should be able to use e.g. sol.rank = reader.GetAttribute("rank");

I don't know if you are coming from a C++ background, but "class" may be
more appropriate than "struct" here, else you could end up with a lot of
problems; I recommend refreshing "value type" versus "reference type".

Additionally, note that this may fit the XmlSerializer very nicely - making
a few changes to fit standard C# naming (although I haven't switched to
properties), you may be able to just use:

[Serializable]
public class Soldier
{
[XmlAttribute("name")]
public string Name; // better as a property
[XmlAttribute("rank")]
public string Rank;
[XmlAttribute("serial")]
public string Serial;
}

And then deserialize the xml as an array of soldiers. Might need a little
tweaking, and I'm not going to bother tilling in blanks unless you are
genuinely interested in this option - but would also save you having to do
much to write them back as xml.

Marc
Nov 30 '06 #3

Each call to Read() will advance the reader to the next node. So you
wan to call Read and then test if the node you found is a soldier node
and if so then you call MoveToFirstAttribute to get the first
attribute, and then MoveToNextAttribute for the following attributes.

Here's a working example. HOWEVER, I would strongly suggest using
XmlSerializer instead of custom XML code. XmlSerializer is easier to
use and writes more efficient code than what I'm showing here.

HTH,

Sam
------------------------------------------------------------
We're hiring! B-Line Medical is seeking Mid/Sr. .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.

using System;
using System.Collections;
using System.IO;
using System.Xml;

namespace CommandTest
{
public class XmlTextReaderAttributes
{
public static void Test()
{
ArrayList soldiers = GetSoldiers();
foreach(soldierStruct sol in soldiers)
{
Console.WriteLine(sol);
}
}

public static ArrayList GetSoldiers()
{
ArrayList soldiers = new ArrayList();
soldiers.Clear();

StringReader text = new StringReader(
@"<?xml version='1.0' encoding='UTF-8'?>
<Soldiers>
<Soldier name='Billy Smith' rank='Private' serial='34' />
<Soldier name='John Jones' rank='General' serial='25' />
</Soldiers>");

XmlTextReader reader = new XmlTextReader(text);
reader.Read();
while (reader.Read())
{
if (reader.Name == "Soldier" &&
reader.MoveToFirstAttribute())
{
soldierStruct sol = new soldierStruct();

do
{
switch (reader.Name)
{
case "name":
sol.name = reader.Value;
break;

case "rank":
sol.rank = reader.Value;
break;

case "serial":
sol.serial = reader.Value;
break;
}
} while (reader.MoveToNextAttribute());

soldiers.Add(sol);
}
}

return soldiers;
}

public struct soldierStruct
{
public string name;
public string rank;
public string serial;

public override string ToString()
{
return rank + " " + name + ", " + serial;
}

}
}
}

Nov 30 '06 #4
sherifffruitfly wrote:
Hi,

I have an xml file with structured like this:

<?xml version="1.0" encoding="UTF-8"?>
<Soldiers>
<Soldier name="Billy Smith" rank="Private" serial="34" />

(a bunch more soldiers)

</Soldiers>

In my program, I have a struct:

public struct soldierStruct
{
public string name;
public string rank;
public string serial;
}

I would like to make a loop that reads however many XML-soldiers there
are into an ArrayList of struct-soldiers. I can come up with the
framework for it, it's just the reading attributes part that I don't
understand how to do. Can anyone help?

Thanks for any suggestions,

cdj

===============
Framework:

public ArrayList GetSoldiers()
{
ArrayList soldiers= new ArrayList();
soldiers.clear();

XmlTextReader reader = new XmlTextReader(path + filename);
reader.Read();
while (reader.Read())
{
soldierStruct sol;

//Stuff here to make sure the reader is
where
//it's supposed to be?????

sol.name = ????? //Need attribute help
somewhere around here
sol.rank = ??????
sol.serial = ??????

soldiers.add(sol)
}

return soldiers;
}
XmlDocument xDoc = new XmlDocument();
xDoc.Load(reader);
XmlNodeList nodes = xDoc.SelectNodes("Soldiers/Soldier");
foreach (XmlNode node in nodes)
{
sol.name = node.Attributes["name"].InnerText;
sol.rank = node.Attributes["rank"].InnerText;
sol.serial = node.Attributes["serial"].InnerText;
}

--
Tom Porterfield
Nov 30 '06 #5

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

Similar topics

1
by: John L. Clark | last post by:
I am curious as to the rationale, and effect, of having default namespaces not applying (directly) to attributes (see http://www.w3.org/TR/REC-xml-names/#defaulting). Given an attribute without a...
7
by: Info 3000 | last post by:
Hello, I'm beginner in XML. I have just a little question : I understand that I can write : <Book> <Title> A nice day </Title> <Author> James Nicepen </Author> </Book>
3
by: Bill C. | last post by:
Hi, I've got a simple console app that just reads an XML file into a DataSet then prints out a description of each table in the DataSet, including column names and row values for each column. ...
6
by: Hans Kamp | last post by:
My program fails reading XML attributes. A fragment of the code is: private void showXmlNodeAtTreeNode(XmlNodeList xnl, TreeNode tn) { int i; for (i = 0; i < xnl.Count; i++) { XmlNode xn =...
9
by: Xarky | last post by:
Hi, I am writing an XML file in the following way. Now I need to read again that file to retrieve data such as Name and Age. Can someone help me out. Thanks in Advance ...
3
by: redefined.horizons | last post by:
I've been reading about Python Classes, and I'm a little confused about how Python stores the state of an object. I was hoping for some help. I realize that you can't create an empty place holder...
0
by: sherifffruitfly | last post by:
I need to do 2 things with a given xml file: (1) Delete a particular element (and all it's decendants), and (2) Edit the attributes of another particular element. Can anyone whip up a quick...
1
by: hodgesp | last post by:
I am VERY New To XML and I am having a heap of trouble writing an application that will allow for the creation, modification and final output in a specific format via C# and asp .net. I am sure I...
1
by: Demon4231 | last post by:
I have a XML file that stores information about an application I am trying to read and it looks like this: <Data> <Login UserName="Username" Password="Password"/> <Application...
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.