December 2007
Intermediate to advanced
896 pages
19h 57m
English
You have data that you want to put into a more structured form, such as an XML document.
Suppose you have the information shown in Table 15-2 for an address book that you want to turn into XML.
Table 15-2. Sample address book data
Name | Phone |
|---|---|
Tim | 999-888-0000 |
Newman | 666-666-6666 |
Harold | 777-555-3333 |
Use XElement to create the XML for this table:
XElement addressBook = new XElement("AddressBook",
new XElement("Contact",
new XAttribute("name", "Tim"),
new XAttribute("phone", "999-888-0000")),
new XElement("Contact",
new XAttribute("name", "Newman"),
new XAttribute("phone", "666-666-6666")),
new XElement("Contact",
new XAttribute("name", "Harold"),
new XAttribute("phone", "777-555-3333")));
// Display XML
Console.WriteLine("Generated XML from XElement:\r\n{0}", addressBook.ToString( ));This method will give you output like this:
<AddressBook> <Contact name="Tim" phone="999-888-0000" /> <Contact name="Newman" phone="666-666-6666" /> <Contact name="Harold" phone="777-555-3333" /> </AddressBook>
Another approach would be to use the XmlWriter to create XML for this table:
XmlWriterSettings settings = new XmlWriterSettings( ); settings.Indent = true; using (XmlWriter writer = XmlWriter.Create(Console.Out, settings)) { writer.WriteStartElement("AddressBook"); writer.WriteStartElement("Contact"); writer.WriteAttributeString("name", "Tim"); writer.WriteAttributeString("phone", "999-888-0000"); writer.WriteEndElement( ); writer.WriteStartElement("Contact"); ...Read now
Unlock full access