Can XmlStarlet preserve CDATA during copy?

2019-08-06 18:57发布

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条回答
祖国的老花朵
2楼-- · 2019-08-06 19:38

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/&lt;!\[CDATA\[/<![CDATA[/g; s/\]\]&gt;/]]>/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
查看更多
登录 后发表回答