XML Literals: Reading an XML File with a Namespace
Tue, Aug 31 2010 23:09
This post covers the technique for reading an XML file that includes an XML namespace (xmlns) attribute.
XML namespaces are used for providing uniquely named elements and attributes in an XML document.
This post continues the series on using XML literals which starts here. Since XML Literals are a VB.NET feature only (new in VB 9/VS 2008), these posts will only include VB.NET code.
The scenario is the same as the prior post, except that the XML file contains an XML namespace attribute. Here is the text from the prior post:
The scenario is that we were given an XML file, maybe from a Web service or from an external application. The code needs to read and process the information in the file. In this case the task is to read the customer names and concatenate them. The results could be displayed in a control such as a ListBox or added to a database or written to another XML file.
So here is the XML in a file named CustomerInfo.xml:
<?xml version="1.0" encoding="utf-8" ?>
Notice the xmlns attribute. This defines a namespace for the XML and ensures that the element names are disambiguated from any other XML elements.
It may seem that the code from the prior post should work fine here as well:
Dim xmlDoc = XDocument.Load("CustomerInfo.xml")
Dim fullName As String
For Each custXML In xmlDoc...<Customer>
fullName = custXML...<LastName>.Value & ", " &
This code first loads the xml from the XML file using the Load method from the XDocument class. It then loops through all of the Customer elements.
The ellipsis (...) means "descendant", so xmlDoc...<Customer> finds all Customer elements that are descendants of the root node. Similarly, custXML...<LastName> finds the descendant element of Customer named LastName and so on.
This code loads the XML without any problems. But the xmlDoc...<Customer> syntax does not find any Customer elements in this case. This is because the XML literals understand the XML namespace provided in the XML document and recognize that the<Customer> XML literal is not associated with that namespace.
The easiest way to associate the XML literals with a namespace is with an Imports statement.
Add this statement to the top of the code file. The xmlDoc...<Customer> syntax then understands that it should use this namespace and it returns the customer elements.
The result in the Debug Window is as follows:
Use this technique any time you need to read an XML file that contains an XML namespace attribute.