2013-03-05 52 views
1

我有數百個xml文件,我想在特定位置執行一次編輯。在每個xml文件中的某處,我看起來像這樣。使用命令行工具進行大量XML編輯

<SomeTag 
    attribute1 = "foo" 
    attribute2 = "bar" 
    attribute3 = "lol"/> 

屬性的數量,以及他們的姓名改爲根據該文件,但SomeTag沒有。我想在最後一個屬性後添加另一個屬性。

我意識到編輯xml這種方式很愚蠢,但它只是一個工作,我想用sed之類的東西來做,但我無法弄清楚多線的用法。

回答

2

兩者可以使用XML殼xsh

for my $file in { glob "*.xml" } { 
    open $file ; 
    for //SomeTag set @another 'new value' ; 
    save :b ; 
} 
3

我會使用轉換樣式表和標識模板(XSLT)。

<xsl:template match="@*|node()"> 
    <xsl:copy> 
    <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 
<xsl:template match="SomeTag"> 
    <xsl:copy> 
    <xsl:attribute name="newAttribute"> 
     <xsl:value-of select="'whatever'"/> 
    </xsl:attribute> 
    <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 

這將複製整個XML,但會通過爲您的'SomeTag'定義的模板運行。

here

1

如果你的輸入文件是真的那麼簡單和一致的格式:

$ cat file 
foo 
    <SomeTag 
    attribute1 = "foo" 
    attribute2 = "bar" 
    attribute3 = "lol"/> 
bar 

$ gawk -v RS='\0' -v ORS= '{sub(/<SomeTag[^/]+/,"&\n  attribute4 = \"eureka\"")}1' file 
foo 
    <SomeTag 
    attribute1 = "foo" 
    attribute2 = "bar" 
    attribute3 = "lol" 
    attribute4 = "eureka"/> 
bar