XML Processing with the XMLReader Object, Part 1 - Digging Deeper
(Page 4 of 5 )
So that takes care of handling elements, but what about the attributes contained within each element? Take a look at this second example, which demonstrates how to process attributes using the XmlTextReader class:
<%@ Page Language="C#"%>
<%@ import namespace="System.Xml"%>
<html>
<head>
<script runat="server">
void Page_Load() {
string strXmlFile =
"http://localhost/xmlpull/library.xml";
// create an instance of the
// XmlTextReader object
XmlTextReader objXmlRdr =
new XmlTextReader(strXmlFile);
// ignore whitespace in the
// XML file
objXmlRdr.WhitespaceHandling =
WhitespaceHandling.None;
String strSpaces;
while(objXmlRdr.Read()) {
// only process the elements
if(objXmlRdr.NodeType ==
XmlNodeType.Element) {
// reset the variable for
// a new node
strSpaces = "";
for(int count = 1;
count <= objXmlRdr.Depth;
count++) {
strSpaces += "===";
}
output.Text += strSpaces + "=> "
+ objXmlRdr.Name;
// check if the element has any
// attributes
if(objXmlRdr.HasAttributes)
{
output.Text += " [";
for(int innercount = 0;
innercount < objXmlRdr.AttributeCount;
innercount++) {
// read the current attribute
objXmlRdr.MoveToAttribute(innercount);
output.Text += objXmlRdr.Name;
}
output.Text += "]";
// instruct the parser to go back
// the element
objXmlRdr.MoveToElement();
}
output.Text += "<br/>";
}
}
// close the object and free up memory
objXmlRdr.Close();
}
</script>
</head>
<body>
<asp:label id="output" runat="server" />
</body>
</html>
Here's the output:

As you can see, there is only one major change to the original code listing - handling attributes for each element that the reader encounters in the XML file:
<%
// check if the element has
// any attributes
if(objXmlRdr.HasAttributes) {
output.Text += " [";
for(int innercount = 0;
innercount < objXmlRdr.AttributeCount;
innercount++) {
// read the current attribute
objXmlRdr.MoveToAttribute(innercount);
output.Text += objXmlRdr.Name;
}
output.Text += "]";
// instruct the parser to
// go back the element
objXmlRdr.MoveToElement();
}
%>
The above code snippet makes for interesting reading. It begins with a check for attributes in the current node using the "HasAttributes" property (this property is set to true if the current node has at least one attribute). The XmlTextReader object's "AttributeCount" property stores the total number of attributes and is useful for looping through the collection of attributes. The MoveToAttribute() method positions the reader at the next attribute in the collection, and the "Name" property is then used to get the name of the attribute. Once iteration through the attributes of the current node is complete, the MoveToElement() method resets the position of the reader, and it then proceeds to the next node (if it exists).
Next: Into the Real World >>
More XML Articles
More By Harish Kamath (c) Melonfire