2017-12-29 50 views
1

私は実際にbashでこれに取り組むための最良のアプローチに関するアドバイスを探しています。XMLファイルの解析と既存のキーに基づく新しいキーの追加

<?xml version="1.0"?> 
<myList> 
    <dataitem> 
     <path>./5553 Subset 43d.zip</path> 
     <name>5553 Subset 43d</name> 
    </dataitem> 
    <dataitem> 
     <path>./Another file name here with spaces.zip</path> 
     <name>Another file name here with spaces</name> 
    </dataitem> 
... 

そして、私はMP4の拡張子を持つ<name>キーのデータを使用して、各<dataitem>に追加のキーを追加したいと思いますので、それは:

私はこのようになりますエントリ1000年代とXMLファイルを持っています

<?xml version="1.0"?> 
<myList> 
    <dataitem> 
     <path>./5553 Subset 43d.zip</path> 
     <name>5553 Subset 43d</name> 
     <video>5553 Subset 43d.mp4</video> 
    </dataitem> 
    <dataitem> 
     <path>./Another file name here with spaces.zip</path> 
     <name>Another file name here with spaces</name> 
     <video>Another file name here with spaces.mp4</video> 
    </dataitem> 
... 

答えて

1

xmlstarletツールを使用して、正しい方法:

次のようになります

出力として次のようになります。

また
<?xml version="1.0"?> 
<myList> 
    <dataitem> 
    <path>./5553 Subset 43d.zip</path> 
    <name>5553 Subset 43d</name> 
    <video>5553 Subset 43d.mp4</video> 
    </dataitem> 
    <dataitem> 
    <path>./Another file name here with spaces.zip</path> 
    <name>Another file name here with spaces</name> 
    <video>Another file name here with spaces.mp4</video> 
    </dataitem> 
... 
+1

(インストールxsltprocのを使用して、ローカルのCDパスを想定)これはそのようなエレガントなソリューションです - 大いに感謝します – ThatDude

+0

@ThatDude、あなたは大丈夫です – RomanPerekhrest

1

XSLTxsltprocにbashの呼び出しで、XMLを変換するために設計された特別な目的の言語を考えます。

XSLT(としての.xslファイル、特殊な.xmlファイルを保存)

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/> 
    <xsl:strip-space elements="*"/> 

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

    <xsl:template match="dataitem"> 
    <xsl:copy> 
     <xsl:copy-of select="*"/> 
     <video><xsl:value-of select="concat(name, '.mp4')"/></video> 
    </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet> 

バッシュ

xsltproc -o Output.xml XSLTScript.xsl Input.xml 
+0

偉大な解決策ですが、私のニーズに少し贅沢です。私が大規模なプロジェクトでこれにどのようにアプローチするかを知ることは良いことです。ありがとうございました – ThatDude

関連する問題