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

xmltextreader filter results based on attribute value

Im trying to output some filtered xml using the xmlTextReader I know
the code and commenting needs cleaned up and eventually plan to add the
values to a dataset. currently what this is doing is matching the
filters, runs into the response.write and outputs nothing. I've used
the dbgclr to verify that the filters are matching and it is hitting
the response.write

what I want it to do is match the filters (an array) and output the
value of fruit so in this case where I pass in the filter(type
attribute) "Apple,Orange.Other" should print "Washington,California -
Granny Smith,[null]"

Here is my sample xml:

<produce>
<fruit type="Apple">Washington</fruit>
<fruit type="Banana">Chiquita</fruit>
<fruit type="Orange">Florida</fruit>
<fruit type="Orange.Other">California</fruit>
</produce>

<produce>
<fruit type="Apple">Granny Smith</fruit>
<fruit type="Orange">Navel</fruit>
</produce>
Here is my C# code:

//Element Name
string element = "fruit";
//Attribute to Check for value
string attributeName = "type";

//Attribute values to look for
string[] filters = new String[2]{"Apple","Orange.Other"};

XmlTextReader xmlReader = new
XmlTextReader(Server.MapPath("Data/mydata.xml"));
while (xmlReader.Read())
{
if (xmlReader.Name.Equals(element) && xmlReader.NodeType !=
XmlNodeType.EndElement)
{
foreach(string currentItem in filters)
{
string holder = xmlReader.GetAttribute(attributeName).ToString();
if(holder == currentItem)
{
Response.Write(xmlReader.Value.ToString());
}
}
}
}
Any help greatly appreciated..if you know of a better way even better!

Nov 12 '05 #1
1 4403
"soupaman" <se********@gmail.com> wrote in message news:11**********************@o13g2000cwo.googlegr oups.com...
Im trying to output some filtered xml using the xmlTextReader
One approach is to subclass an XmlTextReader with these sorts
of filtering capabilities on attribute values. Putting the logic inside
of a subclass (vs. out in an XML application) greatly simplifies
what your XML consumers need to deal with and gives you a
greater deal of re-use.

- - - AttributeFilterXmlTextReader.cs
using System;
using System.Collections;
using System.Xml;

public class AttributeFilterXmlTextReader : XmlTextReader
{
string tagName;
string attrName;
ArrayList attrValues;

public AttributeFilterXmlTextReader(
TextReader reader,
string tagNameOfInterest,
string attrNameOfInterest,
string[] attrValuesOfInterest ) : base( reader)
{
tagName = base.NameTable.Add( tagNameOfInterest);
attrName = base.NameTable.Add( attrNameOfInterest);
attrValues = new ArrayList( attrValuesOfInterest);
}

public override bool Read( )
{
bool result = base.Read( );
if ( result && (this.NodeType == XmlNodeType.Element))
{
if (this.LocalName == tagName)
{
string candidate = this.GetAttribute( attrName);
if ( null != candidate)
{
if ( !attrValues.Contains( candidate))
{
this.Skip( );
result = this.Read( );
}
}
}
}
return result;
}
}
- - -
what I want it to do is match the filters (an array) and output the
value of fruit so in this case where I pass in the filter(type
attribute) "Apple,Orange.Other" should print "Washington,California -
Granny Smith,[null]"
Given the following XML instance document (which is equivalent to your
example but it has to have one document element),

- - - mydata.xml
<?xml version="1.0" encoding="utf-8" ?>
<root>
<produce>
<fruit type="Apple">Washington</fruit>
<fruit type="Banana">Chiquita</fruit>
<fruit type="Orange">Florida</fruit>
<fruit type="Orange.Other">California</fruit>
</produce>
<produce>
<fruit type="Apple">Granny Smith</fruit>
<fruit type="Orange">Navel</fruit>
</produce>
</root>
- - -

Then the following code could be used in an application to load the
filtered XML into an XmlDocument straightaway (for instance in your
Page's PreRender event handler),

// Create a specialized XmlTextReader to filter the instance document.
StreamReader src = File.OpenText( Server.MapPath( "Data//mydata.xml"));
AttributeFilterXmlTextReader afxtr = new AttributeFilterXmlTextReader(
src, "fruit", "type", new string[] { "Apple", "Orange.Other" }
);

// Create an XmlDocument and Load( ) it to drive the Read( ) loop
// around the XmlTextReader so it can do it's filtering thing.
XmlDocument doc = new XmlDocument( );
doc.Load(afxtr);
afxtr.Close( );

// Render as markup (perform necessary translations of '<' so tag names
// are not eaten by the browser, and linefeeds into HTML line-breaks).
Response.Write( doc.OuterXml.Replace( "<", "&lt;").Replace( "\n", "<br />") );
Any help greatly appreciated..if you know of a better way even better!


Another approach you could use is to just load the XML into an
XPathDocument and then query it with XPath expressions or'ing
together the fruit elements of interest. If it's not a large volume of
XML you'll be reading, this may be more easily maintained.

string xpExpr = "/root/produce/fruit[@type='Apple' or @type='Orange.Other']";
XPathDocument xpd = new XPathDocument( Server.MapPath( "Data//mydata.xml"));
XPathNodeIterator nodeSet = xpd.SelectNodes( );
foreach (XPathNavigator nodeNavigator in nodeSet)
{
Response.Write( nodeNavigator.InnerXml + "<br />");
}

XPath expressions can be modified more easily than the logic in an
XmlTextReader subclass, if your requirements may be subject to
change with regard to whether you're performing an intersection
(logical-OR) or union (logical-AND) of filter criteria.
Derek Harmon
Nov 12 '05 #2

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

Similar topics

4
by: Phil Powell | last post by:
http://www.php.net/array_filter I went there at first for my information on filtering mySQL query results using PHP, to no avail. This is more of a Vignette construct (my native environment)...
3
by: Siva | last post by:
Guys - I am a rookie to the field of xml but I have a pressing issue that I hope you can help with. I have an xml document (say runs.xml). I would like to load it in my Vb .net app and search...
4
by: Andy Neilson | last post by:
I've run across a strange behaviour with XmlSerializer that I'm unable to explain. I came across this while trying to use XmlSerializer to deserialize from a the details of a SoapException. This...
2
by: Mitch | last post by:
I have some simple HTML I'm trying to read with the XMLTextReader. As in the MSDS examples, I set up a loop to read each XML node: while (reader.Read()) { switch (reader.NodeType) { case...
0
by: CSDunn | last post by:
Hello, I have a problem with field filtering between an Access 2000 Project form (the application is called CELDT), and the report that shows the results of the filter. Both the form and the...
3
by: Ian Harding | last post by:
I have a class derived from XmlTextReader. It implements the following methods: public override void ReadEndElement() public override void ReadStartElement() public override string ReadString()...
11
by: jason.teen | last post by:
Hi, I dont seem to be able to get this Filter right on my RecordSet for some reason. I have this code: Dim rs As Recordset Set rs = CurrentDb().OpenRecordset("SELECT DISTINCT Product,
1
by: lejason | last post by:
Hi, I have an XML file that is a list of product models and info. The list will eventually contain about 100 products, each product having multiple elements for things like names,...
1
by: woodey2002 | last post by:
Hi Everyone and many thanks for your time.. I am trying to begin access and a bit of VBA i am enjoying it but I have a annoying problem I just can’t get any where on. My databse mostly includes...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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
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: 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...

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.