472,780 Members | 2,090 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,780 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 4360
"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...
0
by: Rina0 | last post by:
Cybersecurity engineering is a specialized field that focuses on the design, development, and implementation of systems, processes, and technologies that protect against cyber threats and...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
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: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
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...
0
by: lllomh | last post by:
How does React native implement an English player?
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth

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.