使用 shell 腳本/指令編輯 xml 文件

使用 shell 腳本/指令編輯 xml 文件

我需要使用 unix 腳本或命令來執行此操作 /home/user/app/xmlfiles 中有一個 xml 文件,例如

<book>
   <fiction type='a'>
      <author type=''></author>
   </fiction>
   <fiction type='b'>
      <author type=''></author>
   </fiction>
   <Romance>
       <author type=''></author>
   </Romance>
</book>

我想將小說中的作者類型編輯為 local 。

   <fiction>
      <author type='Local'></author>
   </fiction>

我需要更改其中的作者類型具有屬性 b 的小說標籤獨自的。請使用 unix shell 腳本或命令幫助我解決這個問題。謝謝 !

答案1

如果您只想替換<author type=''><\/author><author type='Local'><\/author>,可以使用該sed命令:

sed "/<fiction type='a'>/,/<\/fiction>/ s/<author type=''><\/author>/<author type='Local'><\/author>/g;" file

但是,在處理 xml 時,我建議使用 xml 解析器/編輯器,例如xmlstarlet:

$ xmlstarlet ed -u /book/*/author[@type]/@type -v "Local"  file
<?xml version="1.0"?>
<book>
  <fiction>
    <author type="Local"/>
  </fiction>
  <Romance>
    <author type="Local"/>
  </Romance>
</book>

使用該-L標誌來內聯編輯文件,而不是列印變更。

答案2

xmlstarlet edit --update "/book/fiction[@type='b']/author/@type" --value "Local" book.xml

答案3

我們可以使用 xsl 文件doThis.xsl並將其source.xml處理xsltprocnewFile.xml.

xsl基於這個答案問題

將其放入doThis.xsl文件中

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="no"/> 

<!-- Copy the entire document    -->

<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<!-- Copy a specific element     -->

<xsl:template match="/book/fiction[@type='b']/author">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>

<!--    Do something with selected element  -->
            <xsl:attribute name="type">Local</xsl:attribute>

        </xsl:copy>
</xsl:template>

</xsl:stylesheet> 

現在我們生產的是newFile.xml

$:   xsltproc -o ./newFile.xml ./doThis.xsl ./source.xml 

這將是newFile.xml

<?xml version="1.0" encoding="UTF-8"?>
<book>
   <fiction type="a">
      <author type=""/>
   </fiction>
   <fiction type="b">
      <author type="Local"/>
   </fiction>
   <Romance>
       <author type=""/>
   </Romance>
</book>

用來找出 b 類小說的表達式是XPath

答案4

這很容易與sed.以下腳本將更改文件的內容a.xml並將原始文件a.bak作為備份。

它的作用是在每個文件中搜尋該字串<author type=''>並將其替換為<author type='Local'>.修飾符/g意味著如果可能的話,它將嘗試在每行上進行 1 次以上的替換(範例文件不需要)。

sed -i.bak "s/<author type=''>/<author type='Local'>/g" a.xml

相關內容