【问题标题】:Store Tags of XML File in an Array Using Shell Script使用 Shell 脚本将 XML 文件的标签存储在数组中
【发布时间】:2020-07-23 05:08:12
【问题描述】:

我有一个格式如下的 XML 文件:

<classes>

 <subject>
  <name>Operating System</name>
  <credit>3</credit>
  <type>Theory</type>
  <faculty>Prof. XYZ</faculty> 
 </subject>

 <subject>
  <name>Web Development</name>
  <credit>3</credit>
  <type>Lab</type>
 </subject>

</classes>

我想使用 Shell 脚本将标签名称(即姓名、学分、类型、教师)存储在一个数组中。

我尝试使用awk 命令作为:

awk -F'[&lt;&gt;]' '/&lt;name&gt;|&lt;credit&gt;|&lt;type&gt;|&lt;faculty&gt;/{print $2}' file.xml

但它的返回值如下:

name
credit
type
faculty
name
credit
type

如何将这些结果存储在数组中?

【问题讨论】:

    标签: xml shell awk


    【解决方案1】:

    如果您控制了 xml 的来源,我理解手动解析它的诱惑。但是这种方法有很多问题。使用xml库解析xml更安全。

    这是一种使用 libxml 及其命令行界面 xsltproc 的方法:

    xsltproc classes.xsl classes.xml
    

    classes.xsl:

    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="text" />
        <xsl:strip-space elements="*" />
    
        <xsl:template match="/classes/subject/*">
            <xsl:text>&#x09;</xsl:text>
            <xsl:value-of select="name(.)" /><xsl:text>:&#x09;</xsl:text>
            <xsl:value-of select="." /><xsl:text>&#x0a;</xsl:text>
        </xsl:template>
    
        <xsl:template match="/classes/subject/name">
            <xsl:text>'</xsl:text>
            <xsl:value-of select="." />
            <xsl:text>':&#x0a;</xsl:text>
        </xsl:template>
    </xsl:stylesheet>
    

    输入:

    <?xml version="1.0"?>
    <classes><subject><name>Operating System</name><credit>3</credit><type>Theory</type><faculty>Prof. XYZ</faculty></subject><subject><name>Web Development</name><credit>3</credit><type>Lab</type></subject></classes>
    

    输出:

    'Operating System':
        credit: 3
        type:   Theory
        faculty:    Prof. XYZ
    'Web Development':
        credit: 3
        type:   Lab
    

    当我对 xml 进行切片和切块时,有人花时间向我解释了这一点。现在我要付钱了。

    【讨论】:

      【解决方案2】:
      result=($(awk -F'[<>]' '/<name>|<credit>|<type>|<faculty>/{print $2}' file.xml))
      resultlen=${#result[@]}
      echo "resultlen size: ${resultlen}"
      
      for i in "${!result[@]}";
      do 
          echo "Tags ${i} : ${result[i]}"
      done
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-05
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多