Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

Archive for XML

September 2, 2010

XML Literals: Creating XML with a Variable Namespace

Filed under: VB.NET,XML @ 12:24 am

This post covers the technique for creating XML that includes an XML namespace (xmlns) attribute, when that attribute is not predefined at compile time.

This post continues the series on using XML literals which starts here. If you need to create XML with a namespace that is predefined at compile time, you can use the simple technique detailed in this prior post. Since XML literals are a VB.NET feature only (new in VB 9/VS 2008),  this post only includes VB.NET code.

The scenario is the same as the prior post, except that the XML contains an XML namespace attribute that is not known at runtime. Here is the text from the  prior post:

The scenario is that we need to build an XML document, maybe to send to a Web service or to save data to a local file system. In this case, the task is to write customer information, including the customer’s name.

Here is the XML that we want to create:

<Customers xmlns="http://customer/2010/info">
  <Customer>
    <LastName>Baggins</LastName>
    <FirstName>Bilbo</FirstName>
  </Customer>
</Customers>

But the issue is that our requirement states that the namespace (xmlns) can change at runtime. Maybe different Web service vendors need different namespaces or maybe there is a test and production version of the namespace. In any case, you can’t "hard-code" the namespace into the XML literals.

So the trick in this case is to use a "fake" namespace in the XML literals. Then replace the "fake" one with the real one at runtime.

In VB:

Private Function BuildXML(ByVal lastName As String,
                          ByVal firstName As String) As String

    Dim xmlDoc = <Customers xmlns="http://fake-uri.com">
                     <Customer>
                         <LastName><%= lastName %></LastName>
                         <FirstName><%= firstName %></FirstName>
                     </Customer>
                 </Customers>
    Dim realNamespace As String = "
http://customer/2010/info"

    xmlDoc = XElement.Parse(xmlDoc.ToString.
               Replace("
http://fake-uri.com", realNamespace))

    Return xmlDoc.ToString
End Function

Notice the fake namespace (xmlns) attribute. It can contain any namespace name. Using a fake namespace allows you to use XML literals even if you don’t know the namespace at compile time.

Then use the String class Replace method to replace the "fake" namespace with the real one. Working from the inside out, this code takes the XML, converts it to a string, replaces the namespace, then uses the XElement Parse method to convert the string back to XML.

This example still hard-codes the correct namespace into the realNamespace variable, but since it is a variable the value could come from anywhere. It could be read from a table or from a configuration file or be passed in as a command line parameter. (This last part is not really necessary if you plan to pass the result back out of the function as a string as shown in this example.)

Use this technique any time you need to create XML that contains a namespace and you cannot hard-code that namespace into the XML literals.

Enjoy!

[Thanks to Joacim Andersson for the code to accomplish this task!]

September 1, 2010

XML Literals: Creating XML with a Namespace

Filed under: VB.NET,XML @ 11:41 pm

This post covers the technique for creating XML that includes an XML namespace (xmlns) attribute.

From Wikipedia:

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 contains an XML namespace attribute. Here is the text from the  prior post:

The scenario is that we need to build an XML document, maybe to send to a Web service or to save data to a local file system. In this case, the task is to write customer information, including the customer’s name.

Here is the code in VB.NET:

Private Function BuildXML(ByVal lastName As String,
                          ByVal firstName As String) As String
    Dim xmlDoc = <Customers xmlns="
http://customer/2010/info">
                     <Customer>
                         <LastName><%= lastName %></LastName>
                         <FirstName><%= firstName %></FirstName>
                     </Customer>
                 </Customers>
    Return xmlDoc.ToString
End Function

This function passes parameters containing the data for the XML string. In a real application, this could be many customer fields including address and phone information. The function then returns the XML as a string.

The code within the function uses XML literals to build the XML string. Notice how the code mimics the layout of the resulting XML, including the definition of the namespace (xmlns) attribute. Using XML literals in this manner can dramatically simplify creation of XML with less code and fewer errors because you can see how the resulting XML will look.

The <%= expression %> syntax defines an embedded expression. An embedded expression enables you to define an expression within the XML that is evaluated at runtime. So the above code replaces the contents of the specified tags with the parameter values.

This code can be called using syntax like this:

In VB:

Dim xmlResult = BuildXML("Baggins", "Bilbo")

Here is the resulting XML:

<Customers xmlns="http://customer/2010/info">
  <Customer>
    <LastName>Baggins</LastName>
    <FirstName>Bilbo</FirstName>
  </Customer>
</Customers>

Use this technique any time you need to build XML with a namespace in VB.Net.

Enjoy!

XML Literals: Creating XML

Filed under: VB.NET,XML @ 11:05 pm

This post covers the technique for creating XML using XML literals.

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), this post only includes VB.NET code.

The scenario is that we need to build an XML document, maybe to send to a Web service or to save data to a local file system. In this case, the task is to write customer information, including the customer’s name.

Here is the code in VB.NET:

Private Function BuildXML(ByVal lastName As String,
                          ByVal firstName As String) As String
    Dim xmlDoc = <Customers>
                     <Customer>
                         <LastName><%= lastName %></LastName>
                         <FirstName><%= firstName %></FirstName>
                     </Customer>
                 </Customers>
    Return xmlDoc.ToString
End Function

This function passes parameters containing the data for the XML string. In a real application, this could be many customer fields including address and phone information. The function then returns the XML as a string.

The code within the function uses XML literals to build the XML string. Notice how the code mimics the layout of the resulting XML. Using XML literals in this manner can dramatically simplify creation of XML with less code and fewer errors because you can see how the resulting XML will look.

The <%= expression %> syntax defines an embedded expression. An embedded expression enables you to define an expression within the XML that is evaluated at runtime. So the above code replaces the contents of the specified tags with the parameter values.

This code can be called using syntax like this:

In VB:

Dim xmlResult = BuildXML("Baggins", "Bilbo")

Here is the resulting XML:

<Customers>
  <Customer>
    <LastName>Baggins</LastName>
    <FirstName>Bilbo</FirstName>
  </Customer>
</Customers>

Use this technique any time you need to build XML data with VB.Net.

For an example of saving the XML to a file and of building an XML string from a list of objects, see this prior post.

Enjoy!

XML Literals: Reading an XML File with a Variable Namespace

Filed under: VB.NET,XML @ 1:40 am

This post covers the technique for reading an XML file that includes an XML namespace (xmlns) attribute, when that attribute is not predefined at compile time.

This post continues the series on using XML literals which starts here. If you need to read an XML file with a namespace that is predefined at compile time, you can use the simple technique detailed in this prior post. Since XML Literals are a VB.NET feature only (new in VB9/VS 2008), this post only includes VB.NET code.

The title of this post is a little bit of a misnomer because, as far as I could find, you cannot read an XML file using XML literals if the namespace is not predefined at compile time.

So here is the XML in a file named CustomerInfo.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Customers xmlns="
http://customer/2010/info">
  <Customer>
    <LastName>Baggins</LastName>
    <FirstName>Bilbo</FirstName>
  </Customer>
  <Customer>
    <LastName>Baggins</LastName>
    <FirstName>Frodo</FirstName>
  </Customer>
  <Customer>
    <LastName>Gamgee</LastName>
    <FirstName>Sam</FirstName>
  </Customer>
</Customers>

Notice the xmlns attribute defining the namespace.

If you then want to use XML literals to read the file, you must define an Imports statement as shown in the prior post and listed below:

VB.NET:

Imports <xmlns="http://customer/2010/info">

But this code assumes the code has the name of the namespace at compile time. What if the namespace can change depending on the user or test vs. production or the day of the week or the third party application that the XML is coming from? Then you cannot use the Imports statement.

The trick to reading an XML file with a variable XML namespace is to use the XNamespace class.

VB.NET:

Dim ns As XNamespace = "http://customer/2010/info"
For Each custXML In xmlDoc.Descendants(ns + "Customer")
    fullName = custXML.Descendants(ns + "LastName").Value & ", " &
                custXML.Descendants(ns + "FirstName").Value
    Debug.WriteLine(fullName)
Next

This code creates an XNamespace variable. This example still hard-codes the correct namespace into this variable, but since it is a variable the value could come from anywhere. It could be read from a table or from a configuration file or be passed in as a command line parameter.

The XML Descendants method is then used to find the nodes. The Descendants method takes an XName, so you can add the XNamespace to the string name of the element to generate the XName. By using the XNamespace in this manner, the code finds the appropriate elements.

Use this technique any time you need to read an XML file that contains a namespace and you cannot hard-code that namespace into an Imports statement.

Enjoy!

XML Literals: Reading an XML File with a Namespace

Filed under: VB.NET,XML @ 1:09 am

This post covers the technique for reading an XML file that includes an XML namespace (xmlns) attribute.

From Wikipedia:

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" ?>
<Customers xmlns="
http://customer/2010/info">
  <Customer>
    <LastName>Baggins</LastName>
    <FirstName>Bilbo</FirstName>
  </Customer>
  <Customer>
    <LastName>Baggins</LastName>
    <FirstName>Frodo</FirstName>
  </Customer>
  <Customer>
    <LastName>Gamgee</LastName>
    <FirstName>Sam</FirstName>
  </Customer>
</Customers>

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:

VB.NET:

Dim xmlDoc = XDocument.Load("CustomerInfo.xml")
Dim fullName As String

For Each custXML In xmlDoc…<Customer>
    fullName = custXML…<LastName>.Value & ", " &
                      custXML…<FirstName>.Value
    Debug.WriteLine(fullName)
Next

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.

VB.NET:

Imports <xmlns="http://customer/2010/info">

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:

Baggins, Bilbo
Baggins, Frodo
Gamgee, Sam

Use this technique any time you need to read an XML file that contains an XML namespace attribute.

Enjoy!

XML Literals: Reading an XML File II

Filed under: VB.NET,XML @ 12:42 am

This series of posts covers more information on using XML literals. 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 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" ?>
<Customers>
  <Customer>
    <LastName>Baggins</LastName>
    <FirstName>Bilbo</FirstName>
  </Customer>
  <Customer>
    <LastName>Baggins</LastName>
    <FirstName>Frodo</FirstName>
  </Customer>
  <Customer>
    <LastName>Gamgee</LastName>
    <FirstName>Sam</FirstName>
  </Customer>
</Customers>

Here is the code in VB.NET:

Dim xmlDoc = XDocument.Load("CustomerInfo.xml")
Dim fullName As String

For Each custXML In xmlDoc…<Customer>
    fullName = custXML…<LastName>.Value & ", " &
                      custXML…<FirstName>.Value
    Debug.WriteLine(fullName)
Next

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 root node. Similarly, custXML…<LastName> finds the descendant element of Customer named LastName and so on.

The result in the Debug Window is as follows:

Baggins, Bilbo
Baggins, Frodo
Gamgee, Sam

Use this technique any time you need to read data from an XML file.

For more information, click on one of the following links:

Enjoy!

June 7, 2010

Writing to an XML File With Attributes

Filed under: C#,VB.NET,XML @ 10:57 pm

This prior post demonstrated a very simple technique for writing to an XML file that has a set of elements. This post extends that example showing how to write an XML file that has both elements and  attributes.

Here is the XML file created by this example:

<?xml version="1.0" encoding="utf-8"?>
<Employee>
  <LastName>Baggins</LastName>
  <FirstName>Bilbo</FirstName>
  <PhoneNumber PhoneType="Work">(925)555-1234</PhoneNumber>
</Employee>

This XML file has an Employee root node and LastName, FirstName, and PhoneNumber elements. The PhoneNumber element has a PhoneType attribute.

There are several ways to write this file in C# or VB as shown below.

In C# (adding individual nodes):

var doc = new XDocument();

var emp = new XElement("Employee");

emp.Add(new XElement("LastName", textBox1.Text));
emp.Add(new XElement("FirstName", textBox2.Text));

var phone = new XElement("PhoneNumber", textBox3.Text);
phone.Add(new XAttribute("PhoneType", comboBox1.Text));
emp.Add(phone);

doc.Add(emp);

doc.Save("Employee.xml");

This code creates an XML document and adds an Employee root node. It then creates the three elements.

Since the Add method does not return a value, the code needs to create the phone element separately. This provides a reference to that element that can be used to add the attribute.

The Employee element is then added to the XML document and saved.

In C# (using functional construction):

var emp = new XElement("Employee",
    new XElement("LastName", textBox1.Text),
    new XElement("FirstName", textBox2.Text),
    new XElement("PhoneNumber",
        new XAttribute("PhoneType", comboBox1.Text),
        textBox3.Text));

emp.Save("Employee.xml");

Functional construction allows you to create an XML string in a single statement leveraging the XElement and XAttribute constructors. See this msdn link for more information on functional construction.

This example also demonstrates how you can build an XML file without explicitly creating an XDocument object as was done in the prior example.

In C# (using the Parse method):

var emp = XElement.Parse(@"<Employee>
              <LastName>" + textBox1.Text + @"</LastName>
              <FirstName>" + textBox2.Text + @"</FirstName>
              <PhoneNumber PhoneType=’" + comboBox1.Text + "’>" + textBox3.Text + @"</PhoneNumber>
          </Employee>");

emp.Save("Employee.xml");

This example builds the XML using strings. The XML elements, attributes, and values are built up as a single string. Then the Parse method is used to parse the string into an XElement.

The biggest downside of this approach is that concatenating strings in this way can be prone to error. It is best used when you have a pre-defined single string that you want to parse into an XML Element. For example:

XElement newElement  = XElement.Parse(@"<Area name=’Wauwatosa’/>");

[From the post found here.]

In VB (adding individual nodes):

Dim doc = New XDocument()

Dim emp = New XElement("Employee")

emp.Add(New XElement("LastName", TextBox1.Text))
emp.Add(New XElement("FirstName", TextBox2.Text))

Dim phone = New XElement("PhoneNumber", TextBox3.Text)
phone.Add(New XAttribute("PhoneType", ComboBox1.Text))
emp.Add(phone)

doc.Add(emp)

doc.Save("Employee.xml")

This code creates an XML document and adds an Employee root node. It then creates the three elements.

Since the Add method does not return a value, the code needs to create the phone element separately. This provides a reference to that element that can be used to add the attribute.

The Employee element is then added to the XML document and saved.

In VB (using functional construction):

Dim emp = New XElement("Employee",
            New XElement("LastName", TextBox1.Text),
            New XElement("FirstName", TextBox2.Text),
            New XElement("PhoneNumber",
                New XAttribute("PhoneType", ComboBox1.Text),
                TextBox3.Text))

emp.Save("Employee.xml")

Functional construction allows you to create an XML string in a single statement leveraging the XElement and XAttribute constructors. See this msdn link for more information on functional construction.

This example also demonstrates how you can build an XML file without explicitly creating an XDocument object as was done in the prior example.

In VB (using XML literals):

Dim emp = <Employee>
            <LastName><%= TextBox1.Text %></LastName>
            <FirstName><%= TextBox2.Text %></FirstName>
            <PhoneNumber PhoneType=<%= ComboBox1.Text %>>
                           <%= TextBox3.Text %></PhoneNumber>
          </Employee>
emp.Save("Employee.xml")

This example uses XML literals to perform the same operation. It builds the XML string using the <%= %> replacement syntax to populate the value of each element and attribute.

Use any of the above techniques when you need to write values to an XML file with elements and optionally with attributes.

Enjoy!

June 6, 2010

Reading an XML File

Filed under: C#,VB.NET,XML @ 11:23 pm

This prior post detailed how to write to an XML file. This post details how to read that XML file.

The example reads the values and populates three TextBoxes, but you can use this technique to read any information from an XML file.

XML File:

<?xml version="1.0" encoding="utf-8"?>
<Employee>
  <LastName>Baggins</LastName>
  <FirstName>Bilbo</FirstName>
  <PhoneNumber>(925)555-1234</PhoneNumber>
</Employee>

In C#:

var doc = XDocument.Load("Employee.xml");

var emp = doc.Descendants("Employee").FirstOrDefault();

textBox1.Text = emp.Element("LastName").Value;
textBox2.Text = emp.Element("FirstName").Value;
textBox3.Text = emp.Element("PhoneNumber").Value;

In VB:

Dim doc = XDocument.Load("Employee.xml")

Dim emp = doc.Descendants("Employee").FirstOrDefault()

TextBox1.Text = emp.Element("LastName").Value
TextBox2.Text = emp.Element("FirstName").Value
TextBox3.Text = emp.Element("PhoneNumber").Value

In VB using XML Literals:

Dim doc = XDocument.Load("Employee.xml")

TextBox1.Text = doc…<LastName>.Value
TextBox2.Text = doc…<FirstName>.Value
TextBox3.Text = doc…<PhoneNumber>.Value

This code first loads the XML file into an XML document.

In the first two examples, the code finds the first Employee node. In this case, there is only one. It then uses the Element function to retrieve the defined element ("LastName", "FirstName", and "PhoneNumber") from the Employee node. The Value property provides the string value of the element. This value is assigned to the TextBox.

The third example above uses XML literals to retrieve the elements from the XML document. The "…" syntax denotes to search any descendants, so the Employee node does not have to be found first.

Use one of the above techniques any time you need to read values from an XML file.

Enjoy!

Writing to an XML File

Filed under: C#,VB.NET,XML @ 10:57 pm

Sometimes, you just need to write some values to an XML file. If you are targeting the .NET Framework 3.5 or higher, you can use XDocument and XElement to do this easily.

This post demonstrates how to write values to an XML string. The example writes the values from three TextBoxes, but you can use this technique to write any information to an XML file.

In C#:

var doc = new XDocument();

var emp = new XElement("Employee");

emp.Add(new XElement("LastName", textBox1.Text));
emp.Add(new XElement("FirstName", textBox2.Text));
emp.Add(new XElement("PhoneNumber", textBox3.Text));

doc.Add(emp);

doc.Save("Employee.xml");

In VB:

Dim doc = New XDocument()

Dim emp = New XElement("Employee")

emp.Add(New XElement("LastName", TextBox1.Text))
emp.Add(New XElement("FirstName", TextBox2.Text))
emp.Add(New XElement("PhoneNumber", TextBox3.Text))

doc.Add(emp)

doc.Save("Employee.xml")

In VB using XML Literals:

Dim doc = New XDocument()

Dim emp = <Employee>
              <LastName><%= TextBox1.Text %></LastName>
              <FirstName><%= TextBox2.Text %></FirstName>
              <PhoneNumber><%= TextBox3.Text %></PhoneNumber>
          </Employee>
doc.Add(emp)

doc.Save("Employee.xml")

This code first creates a new XDocument that defines the XML document.

In the first two examples, the code then creates a new XElement defining the root node of the XML string. In this case, the root node is "Employee", but it can be anything.

The sub elements are then added to the Employee root element. In this case, the sub elements are "LastName", "FirstName", and "PhoneNumber" and the values of these elements come from the TextBoxes.

The third example above uses XML literals to perform the same operation. It builds the XML string using the <%= %> replacement syntax to populate the value of each element.

In each example, the new Employee element is then added to the XML document and saved.

The resulting XML file is shown below.

XML File:

<?xml version="1.0" encoding="utf-8"?>
<Employee>
  <LastName>Baggins</LastName>
  <FirstName>Bilbo</FirstName>
  <PhoneNumber>(925)555-1234</PhoneNumber>
</Employee>

(See this post for information on reading the above XML file.)

Use one of the above techniques any time you need to write values to an XML file.

Enjoy!

EDIT 6/7/10: To write XML documents that include attributes, see this other post.

March 25, 2010

XML Literals: Handling Empty Elements

Filed under: VB.NET,XML @ 12:31 pm

In this prior post, I covered how to create an XML file using XML literals, a feature new in VB 9 (Visual Studio 2008). In this post, I’ll look at handling empty elements.

If an element value is empty, you can create an empty element in the XML file using the techniques in the prior post mentioned above. But if your requirements are to remove the element if the value is empty, you have a little more code to write.

In VB: (Since C# does not support XML literals, no C# example is provided)

Dim customerXml As XElement = _
    <customers>
      <%= From c In custList _
        Select <customer>
                <LastName><%= c.LastName %></LastName>
                <%= If(String.IsNullOrEmpty(c.FirstName), Nothing, _
                  <FirstName><%= c.FirstName %></FirstName>) %>
                </customer> %>
    </customers>

This code uses the new If ternary operator to assign the XElement <FirstName> or Nothing.

The resulting XML:

<customers>
  <customer>
    <LastName>Jones</LastName>
  </customer>
  <customer>
    <LastName>Baggins</LastName>
    <FirstName>Billbo</FirstName>
  </customer>
  <customer>
    <LastName>Baggins</LastName>
    <FirstName>Frodo</FirstName>
  </customer>
  <customer>
    <LastName>Kurata</LastName>
    <FirstName>Deborah</FirstName>
  </customer>
</customers>

Use this technique any time you need to prevent generation of elements that have empty values.

Enjoy!

Next Page »

© 2014 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs