I Have a property file as below ,
Name=sample
TagName=Test1
TagType=P
Name=sample1
TagName=Test2
TagType=Y
I have a xml file as below ,
<?xml version="1.0" encoding="UTF-8"?>
<root>
</root>
Need to append as below ,
<?xml version="1.0" encoding="UTF-8"?>
<root>
<sub>
<TagName>Test1</TagName>
<TagType>P</TagType>
</sub>
<sub>
<TagName>Test2</TagName>
<TagType>Y</TagType>
</sub>
</root>
Can any one help me to insert in xml file using sed or awk command in shell script ...
Thanks in Advance ..
With bash
and xmlstarlet
. I removed the space before <?xml
in your xml file.
#!/bin/bash
file="file.xml"
prop="property.txt"
while IFS="=" read -r key value; do
[[ "$key" == "Name" ]] && xmlstarlet edit -L --subnode '//root' --type elem -n "sub" "$file"
[[ "$key" == "TagName" ]] && xmlstarlet edit -L --subnode '//root/sub[last()]' --type elem -n "TagName" --value "$value" "$file"
[[ "$key" == "TagType" ]] && xmlstarlet edit -L --subnode '//root/sub[last()]' --type elem -n "TagType" --value "$value" "$file"
done < "$prop"
Output to file.xml:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<sub>
<TagName>Test1</TagName>
<TagType>P</TagType>
</sub>
<sub>
<TagName>Test2</TagName>
<TagType>Y</TagType>
</sub>
</root>
See: xmlstarlet edit
for a quick syntax overview.