welcome/
java-mcmc/
software/
papers/
links/
email me

Writing small XML files

To create a small XML document on the fly, we can use the xml-echo(1) command.


% xml-echo -e "[products/product@price=2.70]Soft Drink"
<?xml version="1.0"?>
<products>
	<product price="2.70">
		Soft Drink
	</product>
</products>

There are a number of things to note here: the indentation is automatic (this could be disabled with the -n switch), and all the tags are properly closed when necessary. The argument string contains instructions for building the XML file structure (these instructions are surrounded by square brackets []).

One way to combine the previous example with the food.xml file is as follows (you don't need to type the backslash \ if you don't split the commands over several lines):


% xml-echo -e "[products/product@price=2.70]Soft Drink" \
        | xml-cat food.xml stdin
<?xml version="1.0"?>
<root>

  <product price="3">Chicken</product>
  <product price="11.50">Lobster</product>
  <product price=".20">Apple</product>
  <product price="1.09">Milk (2 litres)</product>


	<product price="2.70">
		Soft Drink
	</product>
</root>

Note that in general, this output would be passed to a formatting tool to fix the final presentation. xml-coreutils(7) contains just such a tool, called xml-fmt(1).

Here is a second example, which is more complicated, to better see how xml-echo(1) builds up an XML file incrementally and show off some other features.


% xml-echo -en "\i[People/Person@Name=Fred Davis/Address]\i" \
        "\I[LineOne]4 Bushy Street[..]\i" \
        "\I[LineTwo]Green Road[..]\i" \
        "\I[County]Mayo[..]\i" \
        "\I[Country]Ireland[..]" \
        "\I[..]\i" \
        "\I[TelNo]+353 96 45232[..]\i"
<?xml version="1.0"?>
<People>
	<Person Name="Fred Davis">
		<Address>
			<LineOne>4 Bushy Street</LineOne>
			<LineTwo>Green Road</LineTwo>
			<County>Mayo</County>
			<Country>Ireland</Country>
		</Address>
		<TelNo>+353 96 45232</TelNo>
	</Person>
</People>

Just like with echo(1), several strings can be given on the command line, and they will be concatenated by xml-echo prior to being printed. In this example, the indentation of the output is controlled with the -n, \i and \I switches. The -n switch disables automatic indentation, and \i (resp. \I) turns indenting on (resp. off) for the subsequent characters. Although it isn't shown, direct indentation by inserting \t and \n characters is also possible. Finally, the [..] path closes the currently open tag.