- XML Reference Guide
- Overview
- What Is XML?
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- Table of Contents
- The Document Object Model
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- DOM and Java
- Informit Articles and Sample Chapters
- Books and e-Books
- Implementations
- DOM and JavaScript
- Using a Repeater
- Repeaters and XML
- Repeater Resources
- DOM and .NET
- Informit Articles and Sample Chapters
- Books and e-Books
- Documentation and Downloads
- DOM and C++
- DOM and C++ Resources
- DOM and Perl
- DOM and Perl Resources
- DOM and PHP
- DOM and PHP Resources
- DOM Level 3
- DOM Level 3 Core
- DOM Level 3 Load and Save
- DOM Level 3 XPath
- DOM Level 3 Validation
- Informit Articles and Sample Chapters
- Books and e-Books
- Documentation and Implementations
- The Simple API for XML (SAX)
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- SAX and Java
- Informit Articles and Sample Chapters
- Books and e-Books
- SAX and .NET
- Informit Articles and Sample Chapters
- SAX and Perl
- SAX and Perl Resources
- SAX and PHP
- SAX and PHP Resources
- Validation
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- Document Type Definitions (DTDs)
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- XML Schemas
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- RELAX NG
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- Schematron
- Official Documentation and Implementations
- Validation in Applications
- Informit Articles and Sample Chapters
- Books and e-Books
- XSL Transformations (XSLT)
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- XSLT in Java
- Java in XSLT Resources
- XSLT and RSS in .NET
- XSLT and RSS in .NET Resources
- XSL-FO
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- XPath
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- XML Base
- Informit Articles and Sample Chapters
- Official Documentation
- XHTML
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- XHTML 2.0
- Documentation
- Cascading Style Sheets
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- XUL
- XUL References
- XML Events
- XML Events Resources
- XML Data Binding
- Informit Articles and Sample Chapters
- Books and e-Books
- Specifications
- Implementations
- XML and Databases
- Informit Articles and Sample Chapters
- Books and e-Books
- Online Resources
- Official Documentation
- SQL Server and FOR XML
- Informit Articles and Sample Chapters
- Books and e-Books
- Documentation and Implementations
- Service Oriented Architecture
- Web Services
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- Creating a Perl Web Service Client
- SOAP::Lite
- Amazon Web Services
- Creating the Movable Type Plug-in
- Perl, Amazon, and Movable Type Resources
- Apache Axis2
- REST
- REST Resources
- SOAP
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- SOAP and Java
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- WSDL
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- UDDI
- UDDI Resources
- XML-RPC
- XML-RPC in PHP
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- Ajax
- Asynchronous Javascript
- Client-side XSLT
- SAJAX and PHP
- Ajax Resources
- JSON
- Ruby on Rails
- Creating Objects
- Ruby Basics: Arrays and Other Sundry Bits
- Ruby Basics: Iterators and Persistence
- Starting on the Rails
- Rails and Databases
- Rails: Ajax and Partials
- Rails Resources
- Web Services Security
- Web Services Security Resources
- SAML
- Informit Articles and Sample Chapters
- Books and e-Books
- Specification and Implementation
- XML Digital Signatures
- XML Digital Signatures Resources
- XML Key Management Services
- Resources for XML Key Management Services
- Internationalization
- Resources
- Grid Computing
- Grid Resources
- Web Services Resource Framework
- Web Services Resource Framework Resources
- WS-Addressing
- WS-Addressing Resources
- WS-Notifications
- New Languages: XML in Use
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- Google Web Toolkit
- GWT Basic Interactivity
- Google Sitemaps
- Google Sitemaps Resources
- Accessibility
- Web Accessibility
- XML Accessibility
- Accessibility Resources
- The Semantic Web
- Defining a New Ontology
- OWL: Web Ontology Language
- Semantic Web Resources
- Google Base
- Microformats
- StructuredBlogging
- Live Clipboard
- WML
- XHTML-MP
- WML Resources
- Google Web Services
- Google Web Services API
- Google Web Services Resources
- The Yahoo! Web Services Interface
- Yahoo! Web Services and PHP
- Yahoo! Web Services Resources
- eBay REST API
- WordML
- WordML Part 2: Lists
- WordML Part 3: Tables
- WordML Resources
- DocBook
- Articles
- Books and e-Books
- Official Documentation and Implementations
- XML Query
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- XForms
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- Resource Description Framework (RDF)
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- Topic Maps
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation, Implementations, and Other Resources
- Rich Site Summary (RSS)
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- Simple Sharing Extensions (SSE)
- Atom
- Podcasting
- Podcasting Resources
- Scalable Vector Graphics (SVG)
- Informit Articles and Sample Chapters
- Books and e-Books
- Official Documentation
- OPML
- OPML Resources
- Summary
- Projects
- JavaScript TimeTracker: JSON and PHP
- The Javascript Timetracker
- Refactoring to Javascript Objects
- Creating the Yahoo! Widget
- Web Mashup
- Google Maps
- Indeed Mashup
- Mashup Part 3: Putting It All Together
- Additional Resources
- Frequently Asked Questions About XML
- What's XML, and why should I use it?
- What's a well-formed document?
- What's the difference between XML and HTML?
- What's the difference between HTML and XHTML?
- Can I use XML in a browser?
- Should I use elements or attributes for my document?
- What's a namespace?
- Where can I get an XML parser?
- What's the difference between a well-formed document and a valid document?
- What's a validating parser?
- Should I use DOM or SAX for my application?
- How can I stop a SAX parser before it has parsed the entire document?
- 2005 Predictions
- 2006 Predictions
- Nick's Book Picks
With XML so fundamental in Microsoft's .NET framework, it should come as no surprise that the ability to manipulate an XML document is built right into the system. In fact, although DOM Level 2.0 doesn't include a standard way to create or save a document, .NET makes it easy. In this section, we'll get a feel for how these manipulations work by using Visual Basic .NET to load a simple document, make some changes to it, and then save it back out to a file. (We'll be running directly from the command line, so if you're not familiar with GUI programming, don't worry.)
Consider, for example, the following sample file, candy.xml:
<?xml version="1.0"?> <candy> <product>Mints</product> <product>Chocolate</product> <product>Circus Peanuts</product> </candy>
Using .NET, you can create a Document out of it by either feeding the XML directly to the parser, as in:
Option Strict Off Imports System Imports System.IO Imports System.Xml public class ShowFile public shared sub Main() Dim doc as XmlDocument = new XmlDocument() doc.LoadXml("<candy> <product>Mints</product>" _ & "<product>Chocolate</product>" _ & "<product>Circus Peanuts</product></candy>") end sub end class
or reading a file from a URL, as in:
... public shared sub Main() Dim doc as XmlDocument = new XmlDocument() doc.Load("http://www.example.com/candy.xml") end sub ...
Once you create the Document (or in this case, the XmlDocument), you can manipulate it using the .NET binding of the DOM interface, as in:
Option Strict Off Imports System Imports System.IO Imports System.Xml public class ShowFile public shared sub Main() Dim doc as XmlDocument = new XmlDocument() doc.Load("http://www.example.com/candy.xml") dim root as XmlElement = doc.DocumentElement Console.WriteLine("The root element is " + root.Name + ".") dim children as XmlNodeList = root.ChildNodes Console.Write("There are ") Console.Write(children.Count) Console.WriteLine (" child elements.") Console.WriteLine("They are: ") if root.HasChildNodes then for each thisChild as XmlNode in root.ChildNodes if thisChild.NodeType = XmlNodeType.Element then Dim theText as XmlNode theText = thisChild.FirstChild Console.WriteLine(thisChild.Name + ": " + theText.Value) end if next end if end sub end class
First we're getting a reference to the root of the actual Document by asking for the DocumentElement. (Note that in Java, we would use getDocumentElement() rather than referencing the member directly.) We can then access the Name property of that element.
Next, we get an XmlNodeList of all of the child nodes of the root element. That list has a Count property we can use to determine how many children their are. You could, for example, then use this number to iterate through each node directly, but instead let's look at doing it implicitly by calling the objects themselves.
If the root node has children, we can iterate through them by setting thisChild to point to each one in turn. If a node is an element, we can assume (in this case) that it has a text child, which we can then access using the FirstChild member. From there, we can simply print out the values.
We can also use the DOM interface to add information to the Document, as in:
... Console.WriteLine(thisChild.Name + ": " + theText.Value) end if next end if Dim products as XmlNodeList = root.GetElementsByTagName("product") Dim productNode as XmlNode Dim productNum as integer for productNum = 0 to (products.Count - 1) productNode = products.item(productNum) Dim attr as XmlAttribute = doc.CreateAttribute("productNumber") attr.Value = "Product "&productNum Dim productElement as XmlElement = productNode productElement.setAttributeNode(attr) Dim productName as String = productElement.FirstChild.Value productElement.FirstChild.Value = productName.toUpper Dim updateElement as XmlElement = doc.CreateElement("updated") Dim rightNow as DateTime Dim updateText as XmlNode = doc.CreateTextNode(rightNow.Now) updateElement.AppendChild(updateText) productElement.AppendChild(updateElement) Console.WriteLine(productNum) next end sub end class
What we want to do is add an attribute and an element to each product element, so first we can get all of the product elements using GetElementsByTagName(). Next, we can loop through each of them using the Count value, as I mentioned earlier.
For each node, we can create an attribute (using CreateAttribute()) and then assign it a value. From there, you can cast the Node to an Element and assign the Attribute to it. You can also assign the value directly, using:
productElement.SetAttribute("productNumber", "", "Product "&productNum)
Next, we're altering the product name directly by assigning the Text node child of the element a new value.
Finally, we'll make a new Element by asking the Document object to create the it -- that's it's job, according to the DOM specification. We can then create a Text node and append it to the new element, and then append the new element to the product.
Because persisting, or saving, an XML document wasn't part of the DOM specification, every implementation handles it differently, if it handles it at all. For example, in most Java implementations, the easiest way to save an XML Document to a file is to perform an XSL identity tranformation. Fortunately, .NET doesn't make you go through such convolutions, enabling you to simple save() the Document:
... Console.WriteLine(productNum) next doc.save("file:///c:|/output/candyout.xml") Console.WriteLine("Done.") end sub end class
In this case, the end result is a file that shows the appropriate changes, as in:
<candy> <product productNumber="Product 0"> MINTS <updated>1/11/2004 9:37:35 PM</updated> </product> <product productNumber="Product 1"> CHOCOLATE <updated>1/11/2004 9:37:35 PM</updated> </product> <product productNumber="Product 2"> CIRCUS PEANUTS <updated>1/11/2004 9:37:35 PM</updated> </product> </candy>
Note that I've added some text nodes to make the changes easier to see, but the data is the same.
Note that althought I've done these examples in Visual Basic .NET, the core implementation is the same for C# and C++, though of course the syntax is different.