Raj Mullapu February 2016

Adding an element in a XML file without grammatic error

I have a xml file as below

<Rows>
    <row>
        <name>peter</name>
        <id>345</id>
    </row>
    <row>
        <name>matt</name>
        <id>567</id>
    </row>
</Rows>

i have achieved adding a sub element to this file like below:


<Rows>
    <row>
        <name>peter</name>
        <id>345</id>
    </row>
    <row>
        <name>matt</name>
        <id>567</id>
    </row>
<row>
<name>mano</name>
<id>897</id>
</row>
</Rows>

problem is the added element is not exactly in sync with rest of the elements. im expecting same grammar(alignment) as the rest

code tried:

element="\t<row>\n\t <name>NewName</name>\n\t <id>NewID</id>\n\t</row>"
C=$(echo $element | sed 's/\//\\\//g')
echo "after C"
sed "/<\/rows>/ s/.*/${C}\n&/" filename

please assist.

Answers


Michael Back February 2016

Probably the most straightforward answer is to insert records without indentation and use xmllint --format to clean things up after the fact. The proposed solution can also provide error checking that may be very useful to you.

Linux / Unix Command: xmllint

Post Status

Asked in February 2016
Viewed 2,445 times
Voted 8
Answered 1 times

Search




Leave an answer