Shoutout to 2?xml2?

Published: Fri 11 August 2017
By EWS

In Blog.

I'd be remiss in not dedicating a blog post to this handy little utility, designed to allow Unix-heads to extend their honed command-line fu to XML. Let's demonstrate with a small example:

$ echo "/root/=something in here" | 2xml
<root>something in here</root>

2xml takes line-oriented hierarchical data and converts into into XML. 2xml has a convenient brother called xml2 which does the reverse, so, given:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg
 xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
 xml:space="preserve"
 style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision;
 image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
 width="70.5px" height="48px"
 viewBox="0 0 70.5 48"
 font-size="11pt" text-anchor="middle"
 stroke="black" stroke-miterlimit="10" stroke-width="1" fill="none">
<g>
<rect x="0.5" y="0.5" width="67.5" height="45" />
<text stroke-width="0.2pt" fill="black" x="32.285714" y="27.8125">
HW!
</text>
</g></svg>

Then:

cat ex.svg | xml2

yields the following:

/svg/@xmlns=http://www.w3.org/2000/svg
/svg/@xmlns:xlink=http://www.w3.org/1999/xlink
/svg/@xml:space=preserve
/svg/@style=shape-rendering:geometricPrecision; text-rendering:geometricPrecision;  image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd
/svg/@width=70.5px
/svg/@height=48px
/svg/@viewBox=0 0 70.5 48
/svg/@font-size=11pt
/svg/@text-anchor=middle
/svg/@stroke=black
/svg/@stroke-miterlimit=10
/svg/@stroke-width=1
/svg/@fill=none
/svg/g/rect/@x=0.5
/svg/g/rect/@y=0.5
/svg/g/rect/@width=67.5
/svg/g/rect/@height=45
/svg/g/text/@stroke-width=0.2pt
/svg/g/text/@fill=black
/svg/g/text/@x=32.285714
/svg/g/text/@y=27.8125
/svg/g/text=
/svg/g/text=HW!
/svg/g/text=

Of course, the original SVG file that I used was generated using dpic which I have spoken about in a previous article. dpic has no facility to change the font to something else, so a utility-pair like 2xml/xml2 is welcome in doing a little XML post-processing:

cat ex.svg | xml2 | sed '\|/svg/@font|a\
/svg/@font-family=sans-serif
' | 2xml > ex2.svg

The command-line fu above adds an xml2 —format line directly after the font size attribute specifying that a "sans" font be used overall.

Before:

Before

After:

After

Comments !

social