473,503 Members | 13,285 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 7521
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
2260
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
4873
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
9201
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
10424
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
6420
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
3724
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
3085
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
4466
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
1571
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
7212
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
7296
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
7364
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...
1
7017
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7470
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...
0
4696
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...
0
3186
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3174
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1524
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.