Solution:
Si vous voulez juste remplacer <author type=""></author>
avec <author type="Local"></author>
, vous pouvez l’utiliser sed
commander:
sed "/<fiction type="a">/,/</fiction>/ s/<author type=""></author>/<author type="Local"></author>/g;" file
Mais, lorsqu’il s’agit de XML, je recommande un analyseur/éditeur XML comme 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>
Utilisez le -L
flag pour modifier le fichier en ligne, au lieu d’imprimer les modifications.
xmlstarlet edit --update "/book/fiction[@type="b"]/author/@type" --value "Local" book.xml
Nous pourrions utiliser un document xsl doThis.xsl
et traiter le source.xml
avec xsltproc
dans une newFile.xml
.
Le xsl est basé sur la réponse à cette question.
Mettez ceci dans un doThis.xsl
déposer
<?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>
Maintenant, nous produisons le newFile.xml
$: xsltproc -o ./newFile.xml ./doThis.xsl ./source.xml
Ce sera le 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>
L’expression utilisée pour trouver la fiction de type b est XPath
.