【问题标题】:Changing XML node in file with sed or tr or perl使用 sed 或 tr 或 perl 更改文件中的 XML 节点
【发布时间】:2012-02-01 10:10:28
【问题描述】:

我有一个 xml 文件。让我们说带有随机选项卡和空格位置的 sample.xml:

<T1>
     <S1 >  D1 </S1>
 <S1>D2   </  S1>
 < S2 >D3  </S2>
 <S3> D4</S3>
</T1 >

我想把数据和格式改成这样的

<T1>
 <S1>D5</S1>
 <S1>D6</S1>
 <S2>D7</S2>
 <S3>D8</S3>
</T1>

我在 sed 中尝试过,但它不适用于此处的多行情况。 我怎样才能做到这一点。

【问题讨论】:

    标签: xml perl sed awk


    【解决方案1】:

    从文件中删除所有空格,然后使用 xmllint 对其进行格式化

    $ sed 's/[[:space:]]//g' test.xml | xmllint --format -
    <?xml version="1.0"?>
    <T1>
      <S1>D1</S1>
      <S1>D2</S1>
      <S2>D3</S2>
      <S3>D4</S3>
    </T1>
    

    背景

    正如@choroba 所指出的,您的输入数据不是有效的 XML 文件:

    $ cat test.xml
    <T1>
         <S1 >  D1 </S1>
          <S1>D2   </  S1>
           < S2 >D3  </S2>
            <S3> D4</S3>
            </T1 >
    

    xmllint 命令说明了原因:

    $ xmllint test.xml
    test.xml:3: parser error : expected '>'
          <S1>D2   </  S1>
                       ^
    test.xml:3: parser error : Opening and ending tag mismatch: S1 line 3 and unparseable
          <S1>D2   </  S1>
                       ^
    test.xml:4: parser error : StartTag: invalid element name
           < S2 >D3  </S2>
            ^
    test.xml:4: parser error : Opening and ending tag mismatch: T1 line 1 and S2
           < S2 >D3  </S2>
                          ^
    test.xml:5: parser error : Extra content at the end of the document
            <S3> D4</S3>
            ^
    

    【讨论】:

      【解决方案2】:
       sed -r 's/\s//g' yourXML
      

      上面的 sed 行有效吗?

      kent$  cat v.xml
      <T1>
           <S1 >  D1 </S1>
       <S1>D2   </  S1>
       < S2 >D3  </S2>
       <S3> D4</S3>
      </T1 >
      
      kent$  sed -r 's/\s//g' v.xml
      <T1>
      <S1>D1</S1>
      <S1>D2</S1>
      <S2>D3</S2>
      <S3>D4</S3>
      </T1>
      

      您应该确保在您的 xml 文件中,标签和值中没有任何空格。

      【讨论】:

        【解决方案3】:

        &lt;&lt;/ 之后的空格在 XML 中是不允许的。您的 XML 格式不正确,因此无法由专用工具处理。通常,这应该可以工作:

        xmllint --format file.xml
        

        【讨论】:

          【解决方案4】:

          这应该可以 - tr -d ' ' &lt; file

          您的文件:

          [jaypal:~/Temp] cat file
          <T1>
               <S1 >  D1 </S1>
           <S1>D2   </  S1>
           < S2 >D3  </S2>
           <S3> D4</S3>
          </T1 >
          

          测试:

          [jaypal:~/Temp] tr -d ' ' < file
          <T1>
          <S1>D1</S1>
          <S1>D2</S1>
          <S2>D3</S2>
          <S3>D4</S3>
          </T1>
          

          【讨论】:

            猜你喜欢
            • 2021-03-22
            • 2013-10-18
            • 2012-04-17
            • 1970-01-01
            • 1970-01-01
            • 2014-02-08
            • 2017-04-10
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多