View Problem
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=
<item name=
</shopping>
Submit a new solution for ruby, java, perl, groovy ...
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>
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();
}
// 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();
}
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
# -*- 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
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');
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');
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
@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
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()
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()
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)
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)
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;
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;
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();;
#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();;
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)
$ 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)
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>");
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>");
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*))
(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*))
Submit a new solution for ruby, java, perl, groovy ...




