2012-01-03 77 views
0

我有一個xml文件。讓說有標籤和空間的隨機位置sample.xml中:用sed或tr或perl更改文件中的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試過,但它不工作多在線情況如下。 我如何實現同樣的目標。

回答

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> 
     ^
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

在XML中不允許<</之後的空格。您的XML格式不正確,因此無法通過專門的工具進行處理。 Normaly,這應該工作:

xmllint --format file.xml 
+0

+1用於提示xmllint – 2012-01-03 21:03:16

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> 
相關問題