Groups | Blog | Home
all groups > dotnet xml > february 2005 >

dotnet xml : xmltextreader filter results based on attribute value



soupaman
2/12/2005 1:11:36 PM
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!
Derek Harmon
2/13/2005 9:32:35 PM
[quoted text, click to view]

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;
}
}
- - -

[quoted text, click to view]

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 />") );

[quoted text, click to view]

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

AddThis Social Bookmark Button