how to edit XML using bash script?

后端 未结 4 1276
终归单人心
终归单人心 2020-11-29 11:29

1
2

Need to change values 1 and 2 from bash

4条回答
  •  被撕碎了的回忆
    2020-11-29 11:55

    my $0.02 in python because its on every server you will ever log in to

    import sys, xml.etree.ElementTree as ET
    
    data = ""
    for line in sys.stdin:
        data += line
    
    tree = ET.fromstring(data)
    
    nodeA = tree.find('.//tag')
    nodeB = tree.find('.//tag1')
    
    tmp = nodeA.text
    nodeA.text = nodeB.text
    nodeB.text = tmp 
    
    print ET.tostring(tree)
    

    this reads from stdin so you can use it like this:

    $ echo 'hi!this' | python xml_process.py 
    thishi!
    

    EDIT - challenge accepted

    Here's a working xmllib implementation (should work back to python 1.6). As I thought it would be more fun to stab my eyes with a fork. The only think I will say about this is it works for the given use case.

    import sys, xmllib
    
    class Bag:
        pass
    
    class NodeSwapper(xmllib.XMLParser):
        def __init__(self):
        print 'making a NodeSwapper'
        xmllib.XMLParser.__init__(self)
        self.result = ''
        self.data_tags = {}
        self.current_tag = ''
        self.finished = False
    
        def handle_data(self, data):
        print 'data: ' + data
    
        self.data_tags[self.current_tag] = data
        if self.finished:
           return
    
        if 'tag1' in self.data_tags.keys() and 'tag' in self.data_tags.keys():
            b = Bag()
            b.tag1 = self.data_tags['tag1']
            b.tag = self.data_tags['tag']
            b.t1_start_idx = self.rawdata.find(b.tag1)
            b.t1_end_idx = len(b.tag1) + b.t1_start_idx
            b.t_start_idx = self.rawdata.find(b.tag)
            b.t_end_idx = len(b.tag) +  b.t_start_idx 
            # swap
            if b.t1_start_idx < b.t_start_idx:
               self.result = self.rawdata[:b.t_start_idx] + b.tag + self.rawdata[b.t_end_idx:]
               self.result = self.result[:b.t1_start_idx] + b.tag1 + self.result[b.t1_end_idx:]
            else:
               self.result = self.rawdata[:b.t1_start_idx] + b.tag1 + self.rawdata[t1_end_idx:]
               self.result = self.result[:b.t_start_idx] + b.tag + self.rresult[t_end_idx:]
            self.finished = True
    
        def unknown_starttag(self, tag, attrs):
        print 'starttag is: ' + tag
        self.current_tag = tag
    
    data = ""
    for line in sys.stdin:
        data += line
    
    print 'data is: ' + data
    
    parser = NodeSwapper()
    parser.feed(data)
    print parser.result
    parser.close()
    

提交回复
热议问题