Home > Articles > Programming > .NET and Windows Programming

.NET Tools for Working with XML

  • PrintPrint
  • Share ThisShare This
  • DiscussDiscuss
Close Window

Peter Aitken

Learn more…

Debugging 101 for Visual Studio
Sep 15, 2006
Fun with Fractals in Visual Studio .NET
Aug 11, 2006
Exploring Excel Functions, Part 9: Analyzing Frequency Distributions
Aug 4, 2006
File Management in .NET
Jul 7, 2006
Exploring Excel Functions 8: Predicting the Future
Jun 30, 2006
Exploring Excel's Functions, Part 7: Rounding with Excel
Jun 23, 2006
Binary File Access in the .NET Framework
Jun 16, 2006
Text File Access in the .NET Framework
Jun 2, 2006
Using Geometric Transforms for Text Effects in .NET
May 26, 2006
Understanding MDI Applications in .NET
May 12, 2006
A .NET Framework Text and Font Primer
Apr 21, 2006
Exploring Excel's Functions, Part 6: TTEST() Function
Apr 14, 2006
Troubleshooting Excel PivotTables
Apr 7, 2006
Troubleshooting Word Tables
Mar 31, 2006
Exploring Excel's Functions, Part 5: The Power of Choice
Mar 24, 2006
Seven Things I Hate About Word Printing
Mar 10, 2006
Exploring Excel's Functions, Part 4: Database Functions
Feb 24, 2006
Exploring Excel's Functions Part 3: CELL() Shocked
Feb 3, 2006
Exploring Excel's Functions Part 2: ADDRESS() and INDIRECT()
Dec 30, 2005
Exploring Excel's Functions: IF() Only!
Dec 9, 2005
Advanced Find-and-Replace Tools in Word
Oct 28, 2005
Going Beyond Basic Spaces and Hyphens in Word
Sep 16, 2005
Get Organized with Word's Outline Tools
Aug 19, 2005
Managing Your Money in Microsoft Excel: Basic Financial Calculations
Jul 29, 2005
Structured Exception Handling in Visual Studio .NET
Oct 8, 2004
Multithreading with the .NET Framework
Jun 11, 2004
.NET Tools for Working with XML
May 21, 2004
Storing Information: Variables and Constants in C
Mar 28, 2003
Introducing Web Programming with .NET
Mar 1, 2002
Using Web Forms
Mar 1, 2002
Introducing Web Services
Feb 15, 2002
XML and the .NET Framework
Feb 8, 2002
ASP.NET Programming: Using Web Forms
Jan 25, 2002
Understanding the Common Features of Web Controls
Aug 20, 2001

Sorry, this author hasn't posted any blogs.

XML-the Microsoft Way

Like this article? We recommend
XML-the Microsoft Way

.NET provides a powerful set of classes for working with XML directly. This article provides an overview of the most important of these classes, and some examples of what you can do with them.

A lot of people associate the .NET framework with XML, and for good reason. .NET uses XML behind the scenes to implement many of its development tools, such as SOAP and Web services. Beyond that, however, .NET provides a powerful set of classes for working with XML directly. Whatever you need to do with XML—sequential or random access, validation, transforms, or output—the .NET Framework provides you with tools that are not only powerful but easy to use.

This article provides an overview of the most important of these classes, and some examples of what you can do with them. All of .NET's XML classes are in the System.XML namespace, and support the following standards (listed with their WWW namespaces):

XmlTextReader

The XmlTextReader class provides non-cached, forward-only access to a stream of XML data. It is designed specifically for fast access to XML data while placing minimal demands on the systemís resources. Functionally, XmlTextReader is similar to the Simple API for XML (SAX), another technique for reading XML that is popular with non-.NET programmers.

XmlTextReader steps through the XML data one node at a time. At each node, your program can use the class properties to obtain information about the node — its type (element or attribute, for example), data, number of attributes, and so on. You use the read method to advance to the next node, and the EOF property to determine when the end of the data has been reached.

This class does not perform data validation; that's one reason why it is so fast. Nor does it support default attributes or resolve external entities. It does, however, enforce the rules of well-formed XML, which makes it a good well-formedness parser. Because of its speed, it is also well-suited for looking through an XML file for a specific piece of information, or for processing an entire XML file sequentially as when you are generating HTML from the XML data.

Let's look at an example. Listing 1 shows part of an XML data file that will be used in this example. It is data from a checkbook register. Listing 2 shows Visual Basic code that will display the number of checks written to the category "groceries" and the total amount of those checks.

Listing 1. The XML data file used in the examples.

<?xml version="1.0"?>
<checkbook>
<check number="100" date="2004-04-05">
<payee>Wilson Oil Co.</payee>
<amount>156.25</amount>
<category>utilities</category>
</check>
<check number="101" date="2004-04-07">
<payee>Kroger Foods</payee>
<amount>98.25</amount>
<category>groceries</category>
</check>
<check number="102" date="2004-04-07">
<payee>Cancer Society</payee>
<amount>100.00</amount>
<category>charity</category>
</check>
</checkbook>

Listing 2. Using the XmlTextReader class to extract data from an XML file.

Dim rdr As XmlTextReader
Dim amount As String
Dim total As Single = 0
Dim count As Integer = 0
Dim isAmountElement As Boolean
Dim isCategoryElement As Boolean

Try
  rdr = New XmlTextReader("checkbook.xml")
  While rdr.Read()
    ' Look for a start node.
    If rdr.NodeType = XmlNodeType.Element Then
      ' Is it an "amount" or "category" element? 
      'If so set the corresponding flag.
      If rdr.Name = "amount" Then
        isAmountElement = True
      Else
        isAmountElement = False
      End If
      If rdr.Name = "category" Then
        isCategoryElement = True
      Else
        isCategoryElement = False
      End If
    End If
    If rdr.NodeType = XmlNodeType.Text Then
      ' Is it a "category" element with the value "groceries"? If so, increment
      ' the count and add the amount to the total.
      If isCategoryElement And rdr.Value = "groceries" Then
        count += 1
        total += amount
      End If
      ' If it is an "amount" element, save the value for possible future use.
      If isAmountElement Then
      amount = rdr.Value
      End If
    End If
  End While
Catch ex As Exception
  MsgBox("XML error " & ex.Message)
Finally
  If Not rdr Is Nothing Then rdr.Close()
End Try
  MsgBox("You wrote " & count.ToString & " checks for groceries totaling " _
  & Format(total, "C"))
  • Share ThisShare This
  • Your Account

Discussions

Make a New Comment

You must log in in order to post a comment.

Related Resources

Danny KalevMinutes from the October 2009 Meeting
By Danny Kalev on November 19, 2009 No Comments

The minutes from the Santa Cruz (October 2009) meeting are available here. Even if you're not a language layer at heart, I encourage you to read them.

Danny KalevA Reader's Opinion on Attributes
By Danny Kalev on October 20, 2009 No Comments

In August I dedicated a series to the debate about C++0x attributes. I believe that it covered the subject in a balanced and detailed way, but I keep getting complaints from C++ users who don't like attributes for various reasons. Here's a recent email I received from a Polish C++ programmer. While it  doesn't represent my opinion about attributes -- I'm rather neutral about this feature and consider it a "solution waiting for a problem" -- but it suggests that attributes are still a highly controversial issue that will haunt C++ for a long time. The email is quoted here with minor edits that and as usual, with all private details removed.

Danny KalevFollowup: The Web 2.0 Guy I Ain't
By Danny Kalev on October 16, 2009 1 Comment

Almost a year ago, I posted here The Web 2.0 Guy I Ain't. People wonder whether I still resist all those Web 2.0 features and technologies at the end of 2009.

See All Related Blogs

Informit Network