Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

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!

4 Comments

  1.   Richard — June 30, 2010 @ 2:17 pm    Reply

    Your C# Parse example is a *really* bad idea. Aside from the performance impact, you have no idea what text is in the textboxes; if the user types “1 < 3″, your code fails.

  2.   DeborahK — June 30, 2010 @ 5:23 pm    Reply

    Hi Richard –

    Yes, good point. You would have to do some validation before calling that code and if something with a < in it would be valid, you would need to escape them.

    Thanks for your comment.

  3.   Troopers — July 20, 2010 @ 4:34 am    Reply

    Hi,

    Another metod : You can use the XML serialization to write an xml file

  4.   sam — February 15, 2011 @ 6:14 am    Reply

    i am creating an xml document from c# and writing data into the xml with textboxes , for every insert i am getting only one element in the xml document , please give me to insert more than one element into xml

RSS feed for comments on this post. TrackBack URI

Leave a comment

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