シェルスクリプト/コマンドを使用してxmlファイルを編集する

シェルスクリプト/コマンドを使用して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>

フィクションの著者タイプをローカルとして編集したい。

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

著者タイプを変更する必要があります。属性 b を持つフィクションタグ一人で。UNIX シェル スクリプトまたはコマンドを使用して、この問題を解決してください。ありがとうございます。

答え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パーサー/エディターをお勧めします。xmlスターレット:

$ 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.xmlxsltprocに処理することができますnewFile.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

関連情報