问题
How can I make XmlStarlet preserve CDATA when using copy? The <![CDATA[ ]]>
must be maintained because the application that generated (and uses) the data insists on having the CDATA directive around certain data.
Example.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RSLogix5000Content SchemaRevision="1.0" SoftwareRevision="20.01" >
<Controller Use="Target" Name="SOME_TARGET_NAME" ProcessorType="1789-L60">
<Tags>
<Tag Name="gstrScrap" TagType="Base" DataType="STRING" Constant="false" ExternalAccess="Read/Write">
<Data>05 00 00 00 53 43 52 41 50 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00</Data>
<Data Format="String" Length="5">
<![CDATA['SCRAP']]>
</Data>
</Tag>
</Tags>
</Controller>
</RSLogix5000Content>
Using the command;
xml sel -t -c "RSLogix5000Content/Controller/Tags/Tag" Example.xml
Generates data that the application cannot handle because <![CDATA[ ]]>
was removed from around 'SCRAP';
<Tag Name="gstrScrap" TagType="Base" DataType="STRING" Constant="false" ExternalAccess="Read/Write">
<Data>05 00 00 00 53 43 52 41 50 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00</Data>
<Data Format="String" Length="5">
'SCRAP'
</Data>
</Tag>
回答1:
here you go:
xml sel -t -c "RSLogix5000Content/Controller/Tags/Tag" Example.xml >t1.xml
xml ed -i "/Tag/Data/text()" -t text -n "" -v "<![CDATA[" t1.xml >t2.xml
xml ed -a "/Tag/Data/text()" -t text -n "" -v "]]>" t2.xml >t3.xml
sed -r "s/<!\[CDATA\[/<![CDATA[/g; s/\]\]>/]]>/g" t3.xml >t4.xml
you do not need sed unless you have escaped characters in your xml:
xml sel -t -c "RSLogix5000Content/Controller/Tags/Tag" Example.xml >t1.xml
xml ed -i "/Tag/Data/text()" -t text -n "" -v "<![CDATA[" t1.xml >t2.xml
xml ed -a "/Tag/Data/text()" -t text -n "" -v "]]>" t2.xml >t3.xml
xml unesc <t3.xml >t4.xml
来源:https://stackoverflow.com/questions/15400259/can-xmlstarlet-preserve-cdata-during-copy