View Category
XML

Process an XML document

Given the XML Document:

<shopping>
  <item name="bread" quantity="3" price="2.50"/>
  <item name="milk" quantity="2" price="3.50"/>
</shopping>

Print out the total cost of the items, e.g. $14.50
csharp
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(
@"<shopping>
<item name='bread' quantity='3' price='2.50'/>
<item name='milk' quantity='2' price='3.50'/>
</shopping>");

string decimalSeparator= System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;

double sum=0;

foreach(System.Xml.XmlNode nodo in doc.SelectNodes("/shopping/item")){
sum += int.Parse(nodo.Attributes["quantity"].InnerText) * double.Parse(nodo.Attributes["price"].InnerText.Replace(".",decimalSeparator));
}
Console.WriteLine("{0:#.00}",sum);
clojure
(println (format "Total cost of items are $%#.2f"
(->> (xml-seq (parse *xml-input-stream*))
(filter #(= :item (:tag %))) ; Remove all but the item tags
(map :attrs) ; Keep the attributes
(map (fn [e] (str "(* " (:quantity e) " " (:price e) ")"))) ; Get the total price as a sexp
(map read-string) ; "(* quantity price)" -> (* quantity price)
(map eval) ; (* quantity price) -> quantity*price
(apply +)))) ; Sum all elements
cpp
char input[] =
"<shopping>"
" <item name=\"bread\" quantity=\"3\" price=\"2.50\"/>"
" <item name=\"milk\" quantity=\"2\" price=\"3.50\"/>"
"</shopping>";

xml_document<> doc;
doc.parse<0>(input);
xml_node<> *shopping = doc.first_node();

float total_price = 0;
for (xml_node<> *item = shopping->first_node(); item != NULL; item = item->next_sibling())
{
float item_sum = 0;
float val;

if (string(item->name()) != "item")
continue;

for (xml_attribute<> *attr = item->first_attribute(); attr != NULL; attr = attr->next_attribute())
{
string name(attr->name());
if (name == "quantity" || name == "price")
{
stringstream v(attr->value());
v >> val;
if (item_sum)
item_sum *= val;
else
item_sum = val;
}
}
total_price += item_sum;
}

cout.setf(ios::fixed, ios::floatfield);
cout << "Total price is $" << setprecision(2) << total_price << endl;

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>
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>");
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*))
cpp
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;