0

I have a xml file emp.xml

<?xml>
<employee name="abc">ABC</employee>
<employee name="def">DEF</employee>
<!-- abc@gmail.com
this comment is added
to <employee name="gh">
</employee>
-->

?> 

I want to delete some employee details from this file. Employee details to be deleted are mentioned in other file delemp.txt abc gh

while read line
do 
i=\"$line\"
echo $i
find . -name "emp.xml" -type f | xargs sed -i -e '/employee name='$i'/,/<\/employee>/d'

done < delemp.txt

I am reading delemp.txt and getting employee details to be deleted and searching for employee name= and employee end tag but this code is not working

Even if I try

sed -i '/employee name=\"abc\"/,/<\/employee>/d' emp.xml

It is deleting first 2 lines i.e name="abc" and "def"

James Z
  • 12,209
  • 10
  • 24
  • 44
sruthi k
  • 1
  • 2
  • Possible duplicate of [Why it's not possible to use regex to parse HTML/XML: a formal explanation in layman's terms](https://stackoverflow.com/questions/6751105/why-its-not-possible-to-use-regex-to-parse-html-xml-a-formal-explanation-in-la) – Cyrus Apr 03 '19 at 17:23
  • You don't want to use `sed -z 's##\r#g; s#[^\r]*\r##g;s#/r##g' emp.xml`. It might work for simple files, but will fail when small changes are made in the input (maybe after a month or two). – Walter A Apr 05 '19 at 10:22

2 Answers2

0

correcting xml to be valid

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <employee name="abc">ABC</employee>
  <employee name="def">DEF</employee>
  <!-- abc@gmail.com
this comment is added
to <employee name="gh">
</employee>
-->
</root>

using and a proper expression to remove a XML node

xmlstarlet ed -L -d '/root/employee[@name="abc"]' file.xml

result

<?xml version=xmlstarlet ed -L -d '/root/employee[@name="abc"]' file.xml"1.0" encoding="UTF-8"?>
<root>
  <employee name="def">DEF</employee>
  <!-- abc@gmail.com
this comment is added
to <employee name="gh">
</employee>
-->
</root>

finally :

while read name; do
    xmlstarlet ed -L -d "/root/employee[@name='$name']" file.xml
done < names.txt
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

Using in command line :

while read name; do
    xml_grep2 -v "/root/emwantedployee[@name='$name']" file.xml > /tmp/new_file.xml &&
        mv /tmp/new_file.xml file.xml
done < names.txt

Using App::Xml_grep2 (to be installed)

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223