C# -> Read lines from XML file

  • Thread starter Thread starter Hareth
  • Start date Start date
H

Hareth

How can I read lines from an XML file. & add them to a counter.

If possible, words between <page> <\page> is considered as +1 to my counter.

if it isnt possible, I would atlest like to read until the word "explorer"
then add it (+1) to my counter, then read next word, and so on.


Example File:

<?xml version="1.0" encoding="utf-8" ?>
- <Site>
<page>Games - Microsoft Internet Explorer</page>
<page>Cars - Microsoft Internet Explorer</page>
<page>The Biggest And The Best! - Microsoft Internet Explorer</page>
<page>AutoWhatever - Microsoft Internet Explorer</page>
<\Site>


I DONT want to add the following "words" to my counter:

<?xml version="1.0" encoding="utf-8" ?>
- <Site><\Site>
or <page></page>
 
Hello Hareth,
First of all, you shouldn't think about reading "lines" from XML. The whole
idea behind XML is that it is deliniated by element tags, not newlines. I
would use the XMLDocument object to access the nodes:

XmlDocument doc = new XmlDocument();
doc.Load(sPath);

//Then I'd do something like (off the top of my head here):

XmlNodeList nlPages = doc.SelectNodes("//page");

int iCount = nlPages.Count;

It might be faster to use a SAX parser, but I doubt it would be significant.
Tom Clement
Apptero, Inc.
 
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(pathAndFilename);

int count = 0;
XmlNodeList pageNodes = xmlDoc.SelectNodes("*/page");
foreach(XmlNode node in pageNodes)
{
if(node.InnerText.Length > 0)
count++;
}

--Liam.
 
How can I read lines from an XML file. & add them to a counter.

If possible, words between <page> <\page> is considered as +1 to my
counter.

if it isnt possible, I would atlest like to read until the word
"explorer" then add it (+1) to my counter, then read next word, and so
on.


Example File:
Here is an example bit of code that you might be able to adapt:

--------CODE FRAGMENT--------------------------
string xmlpath = "virtualpath";

System.Xml.XmlTextReader myXmlReader;
myXmlReader = new XmlTextReader(xmlpath + "/xmlboard.xml");

while (myXmlReader.Read())
{
if (myXmlReader.NodeType==System.Xml.XmlNodeType.Element)
{
switch ((string) myXmlReader.Name) {
case "page":
counter++;
break;
// other case tests...
// ...
default:
break;
}
}
}
myXmlReader.Close();
----END CODE FRAGMENT---------------------

Bob Dickow
 
Back
Top