Given the following XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response xmlns="...">
<root>
<test>abc</test>
</root>
</response>
I need to add a namespace to each element like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns:response xmlns:ns="...">
<ns:root>
<ns:test>abc</ns:test>
</ns:root>
</ns:response>
Is it possible with sed
? I know sed
is not the best tool for processing XML...
There could be nested nodes, but no one already has the namespace. Finally, there are no attributes.
CodePudding user response:
With such a skinny description of the requirements, you can't do much more than this:
sed 's!</\|<!&ns:!g' your_file
The code
- uses
!
as a separator, so/
needn't be escaped; - the search string matches
</
or<
via the alternation\|
; - the substitution consists of the matched piece itself,
&
, followed byns:
; - all of this is done on the whole line via
g
.
In a comment you said you want to skip the submission on the line starting with <?xml
, but changing the s
command would just make it much longer and less readable.
Since that line is always and only the first, you can instead just target all lines except the first by prepending 2,$
to the s
command.