472,802 Members | 1,317 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

New to XML. Need help reading XML.

Here's my XML:

<?xml version="1.0" ?>
<AppMode Type="Network">
<CurrentFolder Path="c:\tabs">
<Tabs>
<FilePath>tabs\Justin.tab</FilePath>
<FilePath>tabs\Julie.tab</FilePath>
*****There could be 1 of these or 100....quantity can change*****
</Tabs>
</CurrentFolder>
</AppMode>
All I need to do is load "Network" and "c:\tabs" into variables. Then each
FilePath goes into an array.

The following code gives me everything but Julie.tab. It only gives me one
of the FilePaths. I'm not even sure if this is the right/best way to do
this:

Dim XMLReader As XmlTextReader = New XmlTextReader("")
XMLReader.WhitespaceHandling = WhitespaceHandling.None

XMLReader.Read()
XMLReader.Read()
MsgBox(XMLReader.GetAttribute("Type"))

XMLReader.Read()
MsgBox(XMLReader.GetAttribute("Path"))

XMLReader.Read()

While Not XMLReader.EOF *****Why isn't this looping?

XMLReader.Read()

If Not XMLReader.IsStartElement() Then
Exit While
End If

MsgBox(XMLReader.ReadElementString("FilePath"))

End While

XMLReader.Close()

Any help would be greatly appreciated!

Jul 26 '08 #1
5 2096
Justin wrote:
Here's my XML:

<?xml version="1.0" ?>
<AppMode Type="Network">
<CurrentFolder Path="c:\tabs">
<Tabs>
<FilePath>tabs\Justin.tab</FilePath>
<FilePath>tabs\Julie.tab</FilePath>
*****There could be 1 of these or 100....quantity can change*****
</Tabs>
</CurrentFolder>
</AppMode>
All I need to do is load "Network" and "c:\tabs" into variables. Then
each FilePath goes into an array.
One way is to use XPath to find the nodes:

Dim doc As New XPathDocument("..\..\XMLFile1.xml")
Dim nav As XPathNavigator =
doc.CreateNavigator().SelectSingleNode("AppMode")
Dim type As String = nav.GetAttribute("Type", "")
Console.WriteLine("Type: {0}", type)
nav = nav.SelectSingleNode("CurrentFolder")
Dim path As String = nav.GetAttribute("Path", "")
Console.WriteLine("Path: {0}", path)
Dim filePaths As XPathNodeIterator = nav.Select("Tabs/FilePath")
Console.WriteLine("Found {0} file path(s):", filePaths.Count)
Dim paths(filePaths.Count) As String
Dim i As Integer = 0
For Each filePath As XPathNavigator In filePaths
paths(i) = filePath.Value
Console.WriteLine(paths(i))
i = i + 1
Next
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Jul 26 '08 #2
Hi Justin,

From your description, you want to extract some certain values from an XML
document. In .net framework, there is quite rich API support for XML query
and processing. Here you have three different possible means to do it:

1. Use the xmlreader as you've tried, this is a memory efficient approahc,
but maybe more difficult to code(when xml is complex)

2. use XmlDocument + Xpath query, this is quite simple code

3. If you can use .NET 3.5, then "Linq to XML" is quite a good weapon you
can utilize

Here I've produced sample code (extracting the elements you want) for all
of the 3 approaches mentioned above:

===========using XML Reader================
private void btnReader_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(@"..\..\test.xml",
Encoding.UTF8);
XmlReader xr = XmlReader.Create(sr);

List<stringpaths = new List<string>();

while (xr.Read())
{
if (xr.IsStartElement("AppMode"))
{
MessageBox.Show(xr.GetAttribute("Type"));
}else if(xr.IsStartElement("CurrentFolder"))
{
MessageBox.Show(xr.GetAttribute("Path"));
}
else if (xr.IsStartElement("FilePath"))
{
paths.Add(xr.GetAttribute("Path"));
}
}

MessageBox.Show("paths count: " + paths.Count);
sr.Close();
}
=====================

========USE XML document + xpath query==============
private void btnXmlDoc_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(@"..\..\test.xml");

string type =
doc.SelectSingleNode("/AppMode").Attributes["Type"].Value;
string curfolder =
doc.SelectSingleNode("/AppMode/CurrentFolder").Attributes["Path"].Value;

XmlNodeList files = doc.SelectNodes("//FilePath");

List<stringpaths = new List<string>();

foreach (XmlNode pnode in files)
{
paths.Add(pnode.InnerText);
}

MessageBox.Show("type: " + type + "\r\n"
+ "current folder: " + curfolder + "\r\n"
+ "paths count: " + paths.Count);
}
==============================

============ use LINQ TO XML ===================
private void btnLinq_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(@"..\..\test.xml",
Encoding.UTF8);
XDocument xdoc = XDocument.Load(sr);
sr.Close();
string type = xdoc.Element("AppMode").Attribute("Type").Value;
var cfs = from cf in xdoc.Descendants("CurrentFolder")
select cf.Attribute("Path").Value;

string curfolder = cfs.First();

var paths = from fp in xdoc.Descendants("FilePath")
select fp.Value;

List<stringfpaths = paths.ToList();

MessageBox.Show("type: " + type + "\r\n"
+ "current folder: " + curfolder + "\r\n"
+ "paths count: " + fpaths.Count);

}
=============================

if you want to know more about LINQ to XML, please have a look at the MSDN
reference:

#.NET Language-Integrated Query for XML Data
http://msdn.microsoft.com/en-us/library/bb308960.aspx

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsoft.com.

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
--------------------
>From: "Justin" <No**@None.com>
Subject: New to XML. Need help reading XML.
Date: Sat, 26 Jul 2008 00:24:30 -0700
>
Here's my XML:

<?xml version="1.0" ?>
<AppMode Type="Network">
<CurrentFolder Path="c:\tabs">
<Tabs>
<FilePath>tabs\Justin.tab</FilePath>
<FilePath>tabs\Julie.tab</FilePath>
*****There could be 1 of these or 100....quantity can change*****
</Tabs>
</CurrentFolder>
</AppMode>
All I need to do is load "Network" and "c:\tabs" into variables. Then
each
>FilePath goes into an array.

The following code gives me everything but Julie.tab. It only gives me
one
>of the FilePaths. I'm not even sure if this is the right/best way to do
this:

Dim XMLReader As XmlTextReader = New XmlTextReader("")
XMLReader.WhitespaceHandling = WhitespaceHandling.None

XMLReader.Read()
XMLReader.Read()
MsgBox(XMLReader.GetAttribute("Type"))

XMLReader.Read()
MsgBox(XMLReader.GetAttribute("Path"))

XMLReader.Read()

While Not XMLReader.EOF *****Why isn't this looping?

XMLReader.Read()

If Not XMLReader.IsStartElement() Then
Exit While
End If

MsgBox(XMLReader.ReadElementString("FilePath"))

End While

XMLReader.Close()

Any help would be greatly appreciated!

Jul 28 '08 #3
Perfect! Thanks for the info. After reading about 20 pages including MS I
couldn't figure out how to loop at the end.

This worked like a charm!
"Martin Honnen" <ma*******@yahoo.dewrote in message
news:eg**************@TK2MSFTNGP04.phx.gbl...
Justin wrote:
>Here's my XML:

<?xml version="1.0" ?>
<AppMode Type="Network">
<CurrentFolder Path="c:\tabs">
<Tabs>
<FilePath>tabs\Justin.tab</FilePath>
<FilePath>tabs\Julie.tab</FilePath>
*****There could be 1 of these or 100....quantity can change*****
</Tabs>
</CurrentFolder>
</AppMode>
All I need to do is load "Network" and "c:\tabs" into variables. Then
each FilePath goes into an array.

One way is to use XPath to find the nodes:

Dim doc As New XPathDocument("..\..\XMLFile1.xml")
Dim nav As XPathNavigator =
doc.CreateNavigator().SelectSingleNode("AppMode")
Dim type As String = nav.GetAttribute("Type", "")
Console.WriteLine("Type: {0}", type)
nav = nav.SelectSingleNode("CurrentFolder")
Dim path As String = nav.GetAttribute("Path", "")
Console.WriteLine("Path: {0}", path)
Dim filePaths As XPathNodeIterator = nav.Select("Tabs/FilePath")
Console.WriteLine("Found {0} file path(s):", filePaths.Count)
Dim paths(filePaths.Count) As String
Dim i As Integer = 0
For Each filePath As XPathNavigator In filePaths
paths(i) = filePath.Value
Console.WriteLine(paths(i))
i = i + 1
Next
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Jul 29 '08 #4
Thanks for the info Steven. I had already implemented Martins approach.
However I have more XML reading coming up so this is sure to come into play.

Thanks for your time!

"Steven Cheng [MSFT]" <st*****@online.microsoft.comwrote in message
news:bO**************@TK2MSFTNGHUB02.phx.gbl...
Hi Justin,

From your description, you want to extract some certain values from an XML
document. In .net framework, there is quite rich API support for XML query
and processing. Here you have three different possible means to do it:

1. Use the xmlreader as you've tried, this is a memory efficient approahc,
but maybe more difficult to code(when xml is complex)

2. use XmlDocument + Xpath query, this is quite simple code

3. If you can use .NET 3.5, then "Linq to XML" is quite a good weapon you
can utilize

Here I've produced sample code (extracting the elements you want) for all
of the 3 approaches mentioned above:

===========using XML Reader================
private void btnReader_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(@"..\..\test.xml",
Encoding.UTF8);
XmlReader xr = XmlReader.Create(sr);

List<stringpaths = new List<string>();

while (xr.Read())
{
if (xr.IsStartElement("AppMode"))
{
MessageBox.Show(xr.GetAttribute("Type"));
}else if(xr.IsStartElement("CurrentFolder"))
{
MessageBox.Show(xr.GetAttribute("Path"));
}
else if (xr.IsStartElement("FilePath"))
{
paths.Add(xr.GetAttribute("Path"));
}
}

MessageBox.Show("paths count: " + paths.Count);
sr.Close();
}
=====================

========USE XML document + xpath query==============
private void btnXmlDoc_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(@"..\..\test.xml");

string type =
doc.SelectSingleNode("/AppMode").Attributes["Type"].Value;
string curfolder =
doc.SelectSingleNode("/AppMode/CurrentFolder").Attributes["Path"].Value;

XmlNodeList files = doc.SelectNodes("//FilePath");

List<stringpaths = new List<string>();

foreach (XmlNode pnode in files)
{
paths.Add(pnode.InnerText);
}

MessageBox.Show("type: " + type + "\r\n"
+ "current folder: " + curfolder + "\r\n"
+ "paths count: " + paths.Count);
}
==============================

============ use LINQ TO XML ===================
private void btnLinq_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(@"..\..\test.xml",
Encoding.UTF8);
XDocument xdoc = XDocument.Load(sr);
sr.Close();
string type = xdoc.Element("AppMode").Attribute("Type").Value;
var cfs = from cf in xdoc.Descendants("CurrentFolder")
select cf.Attribute("Path").Value;

string curfolder = cfs.First();

var paths = from fp in xdoc.Descendants("FilePath")
select fp.Value;

List<stringfpaths = paths.ToList();

MessageBox.Show("type: " + type + "\r\n"
+ "current folder: " + curfolder + "\r\n"
+ "paths count: " + fpaths.Count);

}
=============================

if you want to know more about LINQ to XML, please have a look at the MSDN
reference:

#.NET Language-Integrated Query for XML Data
http://msdn.microsoft.com/en-us/library/bb308960.aspx

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsoft.com.

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no
rights.
--------------------
>>From: "Justin" <No**@None.com>
Subject: New to XML. Need help reading XML.
Date: Sat, 26 Jul 2008 00:24:30 -0700
>>
Here's my XML:

<?xml version="1.0" ?>
<AppMode Type="Network">
<CurrentFolder Path="c:\tabs">
<Tabs>
<FilePath>tabs\Justin.tab</FilePath>
<FilePath>tabs\Julie.tab</FilePath>
*****There could be 1 of these or 100....quantity can change*****
</Tabs>
</CurrentFolder>
</AppMode>
All I need to do is load "Network" and "c:\tabs" into variables. Then
each
>>FilePath goes into an array.

The following code gives me everything but Julie.tab. It only gives me
one
>>of the FilePaths. I'm not even sure if this is the right/best way to do
this:

Dim XMLReader As XmlTextReader = New XmlTextReader("")
XMLReader.WhitespaceHandling = WhitespaceHandling.None

XMLReader.Read()
XMLReader.Read()
MsgBox(XMLReader.GetAttribute("Type"))

XMLReader.Read()
MsgBox(XMLReader.GetAttribute("Path"))

XMLReader.Read()

While Not XMLReader.EOF *****Why isn't this looping?

XMLReader.Read()

If Not XMLReader.IsStartElement() Then
Exit While
End If

MsgBox(XMLReader.ReadElementString("FilePath"))

End While

XMLReader.Close()

Any help would be greatly appreciated!

Jul 29 '08 #5
Thanks for your reply Justin,

No problem. If you need any help on this later, please feel free to post
here.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
ms****@microsoft.com.

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

--------------------
>From: "Justin" <No**@None.com>
References: <#J**************@TK2MSFTNGP04.phx.gbl>
<bO**************@TK2MSFTNGHUB02.phx.gbl>
>Subject: Re: New to XML. Need help reading XML.
Date: Mon, 28 Jul 2008 21:50:27 -0700
>Thanks for the info Steven. I had already implemented Martins approach.
However I have more XML reading coming up so this is sure to come into
play.
>
Thanks for your time!

"Steven Cheng [MSFT]" <st*****@online.microsoft.comwrote in message
news:bO**************@TK2MSFTNGHUB02.phx.gbl...
>Hi Justin,

From your description, you want to extract some certain values from an
XML
>document. In .net framework, there is quite rich API support for XML
query
>and processing. Here you have three different possible means to do it:

1. Use the xmlreader as you've tried, this is a memory efficient
approahc,
>but maybe more difficult to code(when xml is complex)

2. use XmlDocument + Xpath query, this is quite simple code

3. If you can use .NET 3.5, then "Linq to XML" is quite a good weapon you
can utilize

Here I've produced sample code (extracting the elements you want) for all
of the 3 approaches mentioned above:

===========using XML Reader================
private void btnReader_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(@"..\..\test.xml",
Encoding.UTF8);
XmlReader xr = XmlReader.Create(sr);

List<stringpaths = new List<string>();

while (xr.Read())
{
if (xr.IsStartElement("AppMode"))
{
MessageBox.Show(xr.GetAttribute("Type"));
}else if(xr.IsStartElement("CurrentFolder"))
{
MessageBox.Show(xr.GetAttribute("Path"));
}
else if (xr.IsStartElement("FilePath"))
{
paths.Add(xr.GetAttribute("Path"));
}
}

MessageBox.Show("paths count: " + paths.Count);
sr.Close();
}
=====================

========USE XML document + xpath query==============
private void btnXmlDoc_Click(object sender, EventArgs e)
{
XmlDocument doc = new XmlDocument();
doc.Load(@"..\..\test.xml");

string type =
doc.SelectSingleNode("/AppMode").Attributes["Type"].Value;
string curfolder =
doc.SelectSingleNode("/AppMode/CurrentFolder").Attributes["Path"].Value;

XmlNodeList files = doc.SelectNodes("//FilePath");

List<stringpaths = new List<string>();

foreach (XmlNode pnode in files)
{
paths.Add(pnode.InnerText);
}

MessageBox.Show("type: " + type + "\r\n"
+ "current folder: " + curfolder + "\r\n"
+ "paths count: " + paths.Count);
}
==============================
Jul 29 '08 #6

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

Similar topics

0
by: Bernhard Kuemel | last post by:
Hi! I want to read/write commands and program input to/from /bin/bash several times before I close the stdin pipe. However, reading from cat hangs unless I first close the stdin pipe. <?php...
0
by: dgraper | last post by:
Friends: I'm doing some work for a small government client centralizing data from a bunch of little databases into SQL Server. Everything's been easy except for reading in data from a set of...
2
by: nnimod | last post by:
Hi. I'm having trouble reading some unicode files. Basically, I have to parse certain files. Some of those files are being input in Japanese, Chinese etc. The easiest way, I figured, to distinguish...
66
by: genestarwing | last post by:
QUESTION: Write a program that opens and read a text file and records how many times each word occurs in the file. Use a binary search tree modified to store both a word and the number of times it...
0
by: U S Contractors Offering Service A Non-profit | last post by:
Brilliant technology helping those most in need Inbox Reply U S Contractors Offering Service A Non-profit show details 10:37 pm (1 hour ago) Brilliant technology helping those most in need ...
25
by: vikram Bhuskute | last post by:
I have plans to train some students for C in coming weeks. I am badly looking for C programming assignments fot them. Need 1) lots of them per topiic 2) Should be doable for beginners thanks...
30
by: carlos123 | last post by:
Ok I am working on a Hall Pass program for my computer programming class. There are 3 things that I am confused on. 1. Reading a file. 2. Taking that data read from the file and putting it into...
0
by: Sells, Fred | last post by:
I'm running python 2.5 (or 2.4) in an XP environment. I downloaded and installed the .dll's from OpenLDAP-2.4.8+OpenSSL-0.9.8g-Win32.zip and copied the .dll's in c:/windows/system32 as instructed...
1
by: vijayarl | last post by:
Hi Everyone, i have the written this logic : basically a file operation open (CONFIGFILE, "$config_file") or die; while (<CONFIGFILE>) { chomp;
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.