使用sed或tr或perl更改文件中的XML节点

时间:2012-01-03 10:49:03

标签: xml perl sed awk

我有一个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中尝试过,但它不适用于多行情况,因为这里。 我怎么能实现同样的目标。

4 个答案:

答案 0 :(得分:1)

 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文件中,标签和值中没有任何空格。

答案 1 :(得分:1)

XML中不允许<</之后的空格。您的XML格式不正确,因此无法通过专门工具进行处理。 Normaly,这应该有效:

xmllint --format file.xml

答案 2 :(得分:1)

这应该有效 - tr -d ' ' < 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>

答案 3 :(得分: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>
        ^
相关问题