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

best method of reading XML and adding data to ListView

Joe
Anyone can suggest the best method of reading XML and adding data to
ListView?

Here is the xml data structure::

<xml>
<site>
<url>http://www.yahoo.com</url>
<lastupdate></lastupdate>
<check>1</check>

</site>

<site>
<url>http://www.yahoo.com</url>
<lastupdate></lastupdate>
<check>1</check>

</site>
</xml>

Feb 4 '06 #1
2 7508
Joe,

AFAIK, the ListView doesn't support data binding for the list of items
in it. You will have to manually add the items to the ListView from your
XML.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Joe" <jo*******@yahoo.com> wrote in message
news:%2****************@TK2MSFTNGP11.phx.gbl...
Anyone can suggest the best method of reading XML and adding data to
ListView?

Here is the xml data structure::

<xml>
<site>
<url>http://www.yahoo.com</url>
<lastupdate></lastupdate>
<check>1</check>

</site>

<site>
<url>http://www.yahoo.com</url>
<lastupdate></lastupdate>
<check>1</check>

</site>
</xml>

Feb 5 '06 #2
I guess it really depends on the size of the data and how you are reading it
(stream, string, etc).

If it is small, then loading it into an XmlDocument and using
SelectNodes("site") then SelectSingleNode("url") etc is probaby the easiest
option. If the data is conceivably large and being erad from a stream, then
your best bet is an xml-reader as it is more efficient - but trickier to use
correctly.

If it helps, I have a fragment of code that can help with *exactly* this
very efficiently using a stream, xml-readers and a custom iterator; in usage
you just do (where "reader" is a SimpleXmlReader (my bespoke class) sat on
top of the data-stream:

listView.BeginUpdate();
try {
listView.Items.Clear();
string rowElementName = "site";
string[] fields = new string[] {"url","lastupdate","check"};
foreach (string[] values in reader.ReadElements(rowElementName, true,
fields)) { // true here means "nested" rather than "attributed" fields
listView.Items.Add(new ListViewItem(values));
rows++;
}
} finally {
listView.EndUpdate();
}

It isn't guaranteed to be fool-proof (all flamings welcome if it improves
the code), but even if you only use it as a starting point it might be
handy.

Marc

SimpleXmlReader:
==========
public sealed class SimpleXmlReader : IDisposable {
public static string[] ReadValues(XmlReader reader, bool nested,
params string[] nodeNames) {
Dictionary<string, int> requiredValues = new Dictionary<string,
int>(nodeNames.Length);
int index = 0;
foreach (string nodeName in nodeNames) {
if (!string.IsNullOrEmpty(nodeName)) {
// deliberately breaks if duplicated key requested;
value represents
// position in out array
requiredValues.Add(nodeName, index++);
}
}
string[] result = new string[nodeNames.Length];
string name;
if (nested) {
int targetDepth = reader.Depth + 1;
bool skipped = false;
while (skipped || reader.Read()) {
skipped = false;
int currentDepth = reader.Depth;
if (reader.Depth < targetDepth) {
break; // reached end of element
}
if (currentDepth > targetDepth) { // too deep
reader.Skip();
skipped = true;
} else if (currentDepth == targetDepth &&
reader.NodeType == XmlNodeType.Element) {
name = reader.Name;
if (requiredValues.TryGetValue(name, out index) &&
index >= 0) {
result[index] =
reader.ReadElementContentAsString();
skipped = true; // since this progresses the
cursor!
requiredValues[name] = -1; // stop reading this
}
}
}
} else {
if (reader.MoveToFirstAttribute()) {
do {
name = reader.Name;
if (requiredValues.TryGetValue(name, out index) &&
index >= 0) {
result[index] = reader.Value;
requiredValues[name] = -1; // stop reading this
}
} while (reader.MoveToNextAttribute());
}
}
return result;
}

private Stream _stream;
private readonly bool _leaveOpen;
private bool LeaveOpen { get { return _leaveOpen; } }

public SimpleXmlReader(string path) : this(new FileStream(path,
FileMode.Open), false) { }
public SimpleXmlReader(byte[] data) : this(new MemoryStream(data),
false) { }
public SimpleXmlReader(Stream stream) : this(stream, false) { }
public SimpleXmlReader(Stream stream, bool leaveOpen) {
_stream = stream;
_leaveOpen = leaveOpen;
}

/// <summary>
/// Reads the stream, returning an XmlDocument
/// </summary>
/// <returns>The XmlDocument of the data</returns>
/// <remarks>This will read to the end of the stream, and
/// cannot be repeated</remarks>
public XmlDocument GetDocument() {
XmlDocument doc = new XmlDocument();
doc.Load(_stream);
return doc;
}

private XmlReader _reader;
public XmlReader Reader {
get {
if (_reader == null) {
XmlReaderSettings readerSettings = new
XmlReaderSettings();
readerSettings.CloseInput = !LeaveOpen;
readerSettings.IgnoreComments = true;
_reader = XmlReader.Create(_stream, readerSettings);
}
return _reader;
}
}

public System.Collections.Generic.IEnumerable<string[]>
ReadElements(string rowElementName, bool nested, params string[]
valueNodeNames) {
XmlReader reader = Reader; // creates if not already there

while (reader.ReadToFollowing(rowElementName)) {
yield return ReadValues(reader, nested, valueNodeNames);
}
}

public void Close() {
if (_stream != null) {
if (!LeaveOpen) _stream.Close();
}
if (_reader != null) {
_reader.Close();
}
}
public void Dispose() {
Close();
if (_stream != null) {
if (!LeaveOpen) _stream.Dispose();
_stream = null;
}
if (_reader != null) {
_reader = null;
}
}
}
Feb 5 '06 #3

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

Similar topics

11
by: Dave Smithz | last post by:
Having adopted someone else's PHP cope and completing a crash course in the language I came across a (probably common) problem with the current code. On a registration form, whenever users names...
4
by: David | last post by:
Hello. I am looking for advice on what is "best practice" regarding looping through a form to check its checkboxes and associated data fields. Here is what I am trying to do (Here is the page...
136
by: Matt Kruse | last post by:
http://www.JavascriptToolbox.com/bestpractices/ I started writing this up as a guide for some people who were looking for general tips on how to do things the 'right way' with Javascript. Their...
1
by: Ray Mitchell | last post by:
Hello, In the following code assume that the ListView object "myListView" has been properly created. What I am attempting to do is add a string as a list view item, then read the various string...
7
by: Dave Y | last post by:
I am a newbie to C# and am having trouble trying to override a ListView property method. I have created a new class derived from the Forms.Listview and I cannot figure out the syntax to override...
12
by: Aaron Smith | last post by:
What is the best way to handle data in a multiple user environment? We have forms that will allow users to add edit and delete data from a table on SQL server. The data could be edited on multiple...
13
by: Alan Silver | last post by:
Hello, MSDN (amongst other places) is full of helpful advice on ways to do data access, but they all seem geared to wards enterprise applications. Maybe I'm in a minority, but I don't have those...
9
by: Kadett | last post by:
Hi all, I have following problem: I'm creating a ListView (Details) control at run-time and filling it with some records (let's say 10 000). This operation seems to be quite fast, but when I call...
2
by: JohnH | last post by:
My Customers/Sales/Contacts management database interface is modeled as if Customers are objects, Sales are objects owned by Customer objects, etc. (I'm running Access 11) I have Listviews...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...
0
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,...

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.