duanping2809 2016-11-16 21:31
浏览 62

在多个文件中有条件地替换XML标记

I need to search and replace in multiple xml files. I am looking to write a script to do this job as i have many files to edit. For example,

<search position="after" index="0,1,3" offset="2">
   <![CDATA[
      <?php -- code to be searched -- ?>
           ]]>
</search>
<add>
   <![CDATA[ --code to add here-- ]]>
</add>
I need to change above code to following
<search index="1,2,4">
   <![CDATA[
      <?php -- code to be searched -- ?>
           ]]>
</search>
<add position="after" offset="2">
   <![CDATA[ --code to add here-- ]]>
</add>


I need to

1. move position from search and add tag, position can be 'replace','after','before'.

2. index tag should also be moved to add tag, and incremented as new index starts from 1 instead of zero

3. move offset to add tag

As far as I know Searching for a particular string and replacing is easy using str_replace but i cannot get how to search for a string and replace or append next line and iterating it in all files ending with .xml extension. What is the best way to do it either in php or command line?

  • 写回答

1条回答 默认 最新

  • dougu3290 2016-11-17 08:37
    关注

    Well, first thing to do is to write an XSLT transformation to do this. You really don't want to attempt this at the text level - there are far too many ways of getting it wrong, especially if there are too many files to check each one by hand. The XSLT 2.0 code would be as follows (assuming a wrapper element around search and add which I will call X)

    <xsl:transform version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
    <xsl:template match="X">
     <xsl:copy>
      <search index="{string-join(for $t in tokenize(search/@index, ',') return string(number($t)+1))}">
        <xsl:copy-of select="search/node()"/>
      </search>
      <add position="{search/@position}" offset="{search/@offset}">
        <xsl:copy-of select="add/node()"/>
      </add>
     </xsl:copy>
    </xsl:template>
    
    </xsl:transform>
    

    Then you need to apply this to all files in a directory. If you're using Saxon you can do this from the command line: specify -s:input-dir -o:output-dir.

    评论

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测