Xml文件到CSV输出

时间:2015-02-10 16:15:59

标签: xml bash csv export-to-csv

我有xml文件,格式如下,我想在csv otput中对其进行转换,如下所示。不幸的是,我不允许安装xmlstarlet或其他一些xml解析器(我只有xmllint)。我怎么能这样做,例如,使用,awk,sed ......

     <xn:VsDataContainer id="site00881">
                            <es:listOfNe>SubNetwork=NL1_R,SubNetwork=AHPTUR14,MeContext=rbs008811,ManagedElement=1</es:listOfNe>
                            <es:listOfNe>SubNetwork=NL1_R,SubNetwork=AHPTUR14,MeContext=rbs008819,ManagedElement=1</es:listOfNe>
                </xn:VsDataContainer>
                <xn:VsDataContainer id="site00882">
                            <es:listOfNe>SubNetwork=NL1_R,SubNetwork=AHPTUR14,MeContext=rbs008821,ManagedElement=1</es:listOfNe>

<es:listOfNe>SubNetwork=NL1_R,SubNetwork=AHPTUR14,MeContext=rbs008829,ManagedElement=1</es:listOfNe>
                </xn:VsDataContainer>
                <xn:VsDataContainer id="site00883">
                            <es:listOfNe>SubNetwork=NL1_R,SubNetwork=ASDTUR13,MeContext=rbs008831,ManagedElement=1</es:listOfNe>
                            <es:listOfNe>SubNetwork=NL1_R,SubNetwork=ASDTUR_SIU,MeContext=siu008832,ManagedElement=siu008832</es:listOfNe>
                </xn:VsDataContainer>
                <xn:VsDataContainer id="site00884">
                            <es:listOfNe>SubNetwork=NL1_R,SubNetwork=AHPTUR14,MeContext=rbs008841,ManagedElement=1</es:listOfNe>
                            <es:listOfNe>SubNetwork=NL1_R,SubNetwork=AHPTUR14,MeContext=rbs008849,ManagedElement=1</es:listOfNe>
                </xn:VsDataContainer>

输出应采用csv格式

 rbs008811,site00881
 rbs008819,site00881
 rbs008821,site00882
 rbs008829,site00882
 rbs008831,site00883
 siu008832,site00883
 rbs008841,site00884
 rbs008849,site00884

2 个答案:

答案 0 :(得分:2)

我会帮助您xmllint,但您的xml文件似乎无效。

无论如何,这是一个快速而肮脏的解决方案,你应该避免这样做:

grep -Po "(rbs|site)\d+" file.xml | awk '/site/{site=$1} /rbs/{print $1","site}' 
rbs008811,site00881
rbs008819,site00881
rbs008821,site00882
rbs008829,site00882
rbs008831,site00883
rbs008841,site00884
rbs008849,site00884

答案 1 :(得分:0)

通常对解析XML有所保留:

gawk -v OFS=, '
    match($0, /VsDataContainer id="([^"]+)/, m) {container = m[1]} 
    match($0, /MeContext=([^,]+)/, m)           {print m[1], container}
' file

如果你没有GNU awk:

awk -v OFS=, '
    /VsDataContainer id="/ {
        sub(/.*id="/, "")
        sub(/".*/, "")
        container = $0
    } 
    /MeContext=/ {
        sub(/.*MeContext=/, "")
        sub(/,.*/, "")
        print $0, container
    }
' file