View Problem
XML

create some XML programmatically

Given the following CSV:

bread,3,2.50
milk,2,3.50

Produce the equivalent information in XML, e.g.:

<shopping>
  <item name="bread" quantity="3" price="2.50" />
  <item name="milk" quantity="2" price="3.50" />
</shopping>
ExpandDiskEdit
clojure
(defn list->xml-item [lst]
(let [[name quantity price] (map str lst)]
{:tag :item
:attrs {:name name
:quantity quantity
:price price}}))

(defn cvs->xml [r]
(->> (map #(read-string (str "(" % ")")) (line-seq r))
(map list->xml-item)
(assoc {:tag :shopping} :content)
(emit)
(with-out-str)))

(println (cvs->xml *cvs-reader*))
ExpandDiskEdit
cpp boost+rapidxml
string input("bread,3,2.50\nmilk,2,3.50\n");

tokenizer<char_separator<char> > tokens(input, char_separator<char>(", \n"));
tokenizer<char_separator<char> >::iterator it = tokens.begin();

xml_document<> doc;
xml_node<> *shopping = doc.allocate_node(node_element, "shopping");
doc.append_node(shopping);

while (it != tokens.end()) {
xml_node<> *item = doc.allocate_node(node_element, "item");
shopping->append_node(item);

item->append_attribute(doc.allocate_attribute("name", doc.allocate_string((*it++).c_str())));
item->append_attribute(doc.allocate_attribute("quantity", doc.allocate_string((*it++).c_str())));
item->append_attribute(doc.allocate_attribute("price", doc.allocate_string((*it++).c_str())));
}

cout << doc << endl;
DiskEdit
csharp
string cvs ="bread,3,2.50\nmilk,2,3.50";
IList<string> rows = cvs.Split('\n');

System.Text.StringBuilder sb = new System.Text.StringBuilder("<shopping>");
foreach(string row in rows){
IList<string> data = row.Split(',');
sb.AppendFormat("<item name='{0}' quantity='{1}' price='{2}' />",data[0],data[1],data[2]);
}
sb.Append("</shopping>");
DiskEdit
erlang
to_xml(ShoppingList) ->
Items = lists:map(fun(L) ->
[Name, Quantity, Price] = string:tokens(L, ","),
{item, [{name, Name}, {quantity, Quantity}, {price, Price}], []}
end, string:tokens(ShoppingList, "\n")),
xmerl:export_simple([{shopping, [], Items}], xmerl_xml).
ExpandDiskEdit
fantom
sum := 0.0
rows := CsvInStream(File(`shop.csv`).in).readAllRows

doc := XDoc()
doc.root = XElem("shopping")
{
root := it
rows.each |Str[] row|
{
root.add(XElem("item")
{
XAttr("name", row[0]),
XAttr("quantity", row[1]),
XAttr("price", row[2])
})
}
}

os := File(`shop.xml`).out
doc.write(os)
os.close
DiskEdit
fsharp
#r "System.Xml.dll"
#r "System.Xml.Linq.dll"

open System
open System.Xml
open System.Xml.Linq

let data = "bread,3,2.50
milk,2,3.50"

let X name =
XName.Get(name)

let lines = data.Split( [|"\n" |], StringSplitOptions.RemoveEmptyEntries)

let document = new XDocument()
let element = new XElement(X "shopping")
document.Add(element)

lines
|> Seq.iter (fun line ->
let items = line.Split([|','|])
let item = new XElement(X "item",
new XAttribute(X "name", items.[0]),
new XAttribute(X "quantity", items.[1]),
new XAttribute(X "price", items.[2]))
element.Add(item))

let output = document.ToString();;
ExpandDiskEdit
groovy
b = new groovy.xml.MarkupBuilder()
b.shopping {
csv.eachLine { line ->
(n, q, p) = line.split(',')
item(name:n, quantity:q, price:p)
}
}
ExpandDiskEdit
groovy
// Groovy equivalent of Java JAXB solution
@XmlAccessorType(NONE)
class Item {
@XmlAttribute String name
@XmlAttribute Integer quantity
@XmlAttribute Double price
}

@XmlAccessorType(NONE)
@XmlRootElement
class Shopping {
@XmlElement Set<Item> items = []
}

Shopping shopping = new Shopping()
csvtext.eachLine{ line ->
(n, q, p) = line.split(',')
shopping.items << new Item(name:n, quantity:q.toInteger(), price:p.toDouble())
}
JAXB.marshal shopping, System.out
ExpandDiskEdit
java >= 1.6
// In this solution JAXB is used to created the xml output.
// JAXB is included in Java 1.6. Runs with 1.5 if you include JAXB Jars
// in the classpath.
class Item {
// Of course you use getters and setters and declare attributes private.
// In this sample a "dirty" way is chosen to keep LOC low.
@XmlAttribute
String name;
@XmlAttribute
Integer quantity;
@XmlAttribute
Double price;
}

@XmlRootElement
class Shopping {
@XmlElement
Set<Item> items = new HashSet<Item>();
}

String line = null;
Shopping shopping = new Shopping();
try {
BufferedReader reader = new BufferedReader(new FileReader("shopping.csv"));
while ((line = reader.readLine()) != null) {
String[] parts = line.split(",");
Item item = new Item();
item.name = parts[0];
item.quantity = Integer.parseInt(parts[1]);
item.price = Double.parseDouble(parts[2]);
shopping.items.add(item);

}
JAXB.marshal(shopping, "D:" + File.separatorChar + "shopping.auto.xml");
} catch (IOException e) {
e.printStackTrace();
}
DiskEdit
ocaml
(* Compilation (native):
$ ocamlopt -I +csv csv.cmxa -I +xml-light xml-light.cmxa csv2xml.ml -o csv2xml
*)

let () =
let table = Csv.load "shopping.csv" in
let columns = ["name"; "quantity"; "price"] in

let xml = Xml.Element ("shopping", [],
List.rev (
List.fold_left (fun acc row ->
Xml.Element ("item",
List.combine columns row, []) :: acc) [] table)) in

print_endline (Xml.to_string_fmt xml)
DiskEdit
perl
#! /usr/bin/perl
# -*- Mode: CPerl -*-

use strict;
use XML::Simple;
use Data::Dumper;

# bread,3,2.50
# milk,2,3.50
#
# Produce the equivalent information in XML, e.g.:
#
# <shopping>
# <item name="bread" quantity="3" price="2.50" />
# <item name="milk" quantity="2" price="3.50" />
# </shopping>
#

my $line;
my $item;
my $q;
my $p;
my $z;

my $xs = XML::Simple->new();
my %d = ();
while($line=<DATA>){
chomp $line;
($item,$q,$p) = split ",",$line;
$d{shopping}{item}{$item}{quantity} = $q;
$d{shopping}{item}{$item}{price} = $p;
}

$xml = $xs->XMLout(\%d, KeepRoot => 1);
print $xml,"\n";

__DATA__
bread,3,2.50
milk,2,3.50
DiskEdit
perl
use strict;
use XML::Writer;
use Text::CSV;

my $csv = <<ENDOFCSV;
bread,3,2.50
milk,2,3.50
ENDOFCSV

open my $fh, '<', \$csv or die "Can't open string, $!\n";
my $csv = Text::CSV->new;
my $writer = XML::Writer->new(DATA_MODE => 1, DATA_INDENT => 2);

$writer->startTag('shopping');

while (my $arr_ref = $csv->getline($fh)) {
my %attributes;
@attributes{qw/name quantity price/} =
@{$arr_ref}[0..2];
$writer->emptyTag('item' => %attributes)
}
$writer->endTag('shopping');


ExpandDiskEdit
php
$xmllines = split("\n", $cvs);
foreach ($xmllines as $l) {
$xml[] = split(",", $l);
}
echo "<shopping>\n";
foreach ($xml as $x) {
echo "\t<item name=\"".$x[0]."\" quantity=\"".$x[1]."\" price=\"".$x[2]."\" />\n";
}
echo "</shopping>\n";
DiskEdit
python
from xml.dom import minidom

csv = """bread,3,2.50
milk,2,3.50"""

doc = minidom.Document()
shopping = doc.createElement("shopping")

for line in csv.split("\n"):
name, quantity, price = line.split(",")
el = doc.createElement("item")
el.setAttribute("name", name)
el.setAttribute("quantity", quantity)
el.setAttribute("price", price)
shopping.appendChild(el)

print shopping.toprettyxml()
DiskEdit
python python 2.5+
from xml.etree.ElementTree import Element, SubElement, tostring

csv = """bread,3,2.50
milk,2,3.50"""

root = Element('shopping')

for line in csv.split("\n"):
name, quantity, price = line.split(",")
SubElement(root,'item', {'name' : name,
'quantity' : quantity,
'price' : price })

print tostring(root)
DiskEdit
ruby
# gem install builder
require 'builder'

xml = Builder::XmlMarkup.new
xml.shopping do
xml.item(:name => "bread", :quantity => 3, :price => "2.50")
xml.item(:name => "milk", :quantity => 2, :price => "3.50")
end
xml
ExpandDiskEdit
scala
<shopping>
{List("bread,3,2.50", "milk,2,3.50") map { row =>
row split ","
} map { item =>
<item name={item(0)} quantity={item(1)} price={item(2)}/>
}}
</shopping>

Submit a new solution for clojure, cpp, csharp, erlang ...