How to Modify the XML segment using Python?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • roberttonafelix
    New Member
    • Oct 2012
    • 16

    How to Modify the XML segment using Python?

    Hi Friends,

    i have an xml file which has some data as below...

    <ZACGPIAD SEGMENT="1">
    <IDENTIFIER>D00 0</IDENTIFIER>
    <CUST_DEL_NO/>
    <CUST_DEL_DAT E/>
    <TRUCKNO/>
    <DRIVERNAME/>
    <DRIVERID/>
    <RESPONS_OFF/>
    <CONFIRM_DATE>$ &gt;ñô«xr</CONFIRM_DATE>
    <SERIAL_NO>9</SERIAL_NO>
    <SERIAL_CHAR/>
    <DEL_INFO1/>
    <QTY>0</QTY>
    <DEL_INFO2/>
    <QTY>0</QTY>
    <DEL_INFO3/>
    <QTY>0</QTY>
    <TRANS_COMPANY> 0</TRANS_COMPANY>
    </ZACGPIAD>

    this segment is need to be changed as shown below...

    <ZACGPIADD SEGMENT="1">
    <IDENTIFIER>D00 0</IDENTIFIER>
    <CUST_DEL_NO/>
    <CUST_DEL_DAT E/>
    <TRUCKNO/>
    <DRIVERNAME/>
    <DRIVERID/>
    <RESPONS_OFF/>
    <CONFIRM_DATE>$ &gt;ñô«xr</CONFIRM_DATE>
    <SERIAL_NO>9</SERIAL_NO>
    <SERIAL_CHAR/>
    <DEL_INFO1/>
    <QTY1>0</QTY1>
    <DEL_INFO2/>
    <QTY2>0</QTY2>
    <DEL_INFO3/>
    <QTY3>0</QTY3>
    <TRANS_COMPANY> 0</TRANS_COMPANY>
    </ZACGPIADD>

    i can able to change the segment name but that <QTY> tag i dont have any idea that how to make this using python...

    Kindly guide me if it is possible to do...

    Thanks in advance,

    Robert.J
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Do you want to change the text node value enclosed by a certain tag such as "QTY1"?

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Assuming your answer to my question is in the affirmative, given a parent node "parent", change the following text node to the value "text".
      Code:
          def setTextElem(self, parent, text):
              '''Set the first child text element data of parent element. Parent
              and child must be of the form "<head_diam>1.375</head_diam>".'''
              success = False
              for n in parent.childNodes:
                  # TEXT_NODE - 3
                  if n.nodeType == 3:
                      n.data = text
                      success = True
              return success
      The above is a method of an XML parser class. This only changes the document object in memory - you will need to write the document to disc to make the change permanent.

      Comment

      • roberttonafelix
        New Member
        • Oct 2012
        • 16

        #4
        thanks for the reply....

        i need to change that <QTY> tag to <QTY1>,<QTY2>,< QTY3>....

        Comment

        • bvdet
          Recognized Expert Specialist
          • Oct 2006
          • 2851

          #5
          That's a bit more involved. I'm not an XML expert, so there may be a better way. Create a new node element with the name you want and child text node. Get the parent node and the node you want to replace and apply xml doc method replaceChild. Following is an example:

          Parser is an xml parser class.
          Code:
          >>> a = Parser("test.xml")
          >>> print a.backToXML()
          <?xml version="1.0" ?>
          <person_details>
            <person>
              <name>Mary</name>
              <location> loc1 </location>
            </person>
          </person_details>
          >>> n = a.doc.getElementsByTagName("name")[0]
          >>> n1 = a.doc.getElementsByTagName("person")[0]
          >>> new = a.doc.createElement("name1")
          >>> new.appendChild(a.doc.createTextNode("XYZ"))
          <DOM Text node "'XYZ'">
          >>> n1.replaceChild(new, n)
          <DOM Element: name at 0x610c2c8>
          >>> print a.backToXML()
          <?xml version="1.0" ?>
          <person_details>
            <person>
              <name1>XYZ</name1>
              <location> loc1 </location>
            </person>
          </person_details>
          >>>

          Comment

          • roberttonafelix
            New Member
            • Oct 2012
            • 16

            #6
            thanks for the reply dude....

            but i complete myself using replace....

            here is the code which i created....

            Code:
            import os, glob
            import time
            from datetime import datetime
            now=datetime.now()
            filepath = "*****************"
            os.chdir(filepath)
            for files in glob.glob("*.*"):
                r0=now.strftime("%Y/%m/%d-%H:%M:%S")
                curdate=now.strftime("%d-%m-%Y")
                filename=filepath+files
                file1 = open(filename,'r')
                file3=str(file1.read())
                file2 = open("*********"+files,'w')
                string0=file3.replace('<ZACGPIAD SEGMENT="1">','<ZACGPIADD SEGMENT="1">')
                string1=string0.replace('</ZACGPIAD>','</ZACGPIADD>')
                string2=string1.replace('<QTY>','<QTY1>', 1)
                string3=string2.replace('</QTY>','</QTY1>', 1)
                string4=string3.replace('<QTY>','<QTY2>', 1)
                string5=string4.replace('</QTY>','</QTY2>', 1)
                string6=string5.replace('<QTY>','<QTY3>', 1)
                string7=string6.replace('</QTY>','</QTY3>', 1)
                file2.write(string7)
                print files + " Done"
                file2.close()
                filename1=curdate+"_"+"invoicefiles.txt"
                log=file("D:\\Invoice_transfer\\Log\\"+filename1,"a+")
                print >> log,"File name: "+ filename +" Processed time: "+r0
                log.close()
            else:
                print "No files found"
            Last edited by Rabbit; May 4 '13, 03:33 AM. Reason: Please use code tags when posting code.

            Comment

            • bvdet
              Recognized Expert Specialist
              • Oct 2006
              • 2851

              #7
              roberttonafelix ,

              Whatever works for you! Working with text files, str replace would typically be the way to do it. I would prefer an XML parse solution when working with XML though.

              Comment

              Working...