
我在整個目錄中分佈著大約 350 個 XML 檔案/abc
。我想找到 alt 屬性的值恰好是 ' 的所有實例巴拉':
<image alt="blah blah" src="../webcontent/filename.png">
<caption>
Figure 1.1: Typical Components of Blah Blah
</caption>
</image>
並將屬性的值替換alt
為包含的內容caption
(刪除換行符號)
<image alt="Figure 1.1: Typical Components of Blah Blah" src="../webcontent/filename.png">
<caption>
Figure 1.1: Typical Components of Blah Blah
</caption>
</image>
我願意在 Ubuntu 或 Windows 上執行腳本,或使用任何文字編輯工具。
假設換行符和縮排一致是不安全的。此外,並非所有圖像都有標題。路徑中的所有 XML 文件都是格式正確的。
有沒有一種簡單的方法可以就地編寫此替換腳本?我願意接受適用於單一文件的東西;我可以將其擴展為遞歸運行。
答案1
對於單一文件,以下 XSLT 樣式表將完成此工作:
<t:transform version="1.0" xmlns:t="http://www.w3.org/1999/XSL/Transform">
<t:template match="node()|@*">
<t:copy>
<t:apply-templates select="node()|@*"/>
</t:copy>
</t:template>
<t:template match="image/@alt[. = 'blah blah']">
<t:attribute name="alt" select="normalize-space(../caption)"/>
</t:template>
</t:transform>
要處理多個文件,您可以從某些shell 腳本、Ant 腳本或類似腳本(或查看xmlsh)多次呼叫樣式表,或者如果您使用的是XSLT 2.0 處理器(例如Saxon),則可以在XSLT 本身內編寫它的腳本使用collection()函數
答案2
您也可以使用xmlstarlet
:
xmlstarlet ed -u '//image/@alt[.= "blah blah"]' -x "normalize-space(../caption/text())"