Skriptcode

www.altova.com Dieses Kapitel drucken Eine Ebene nach oben

Startseite > 

Skriptcode

Das folgende mit Anmerkungen versehene Python-Skript verarbeitet Daten in der Datei NanonullOrg.xml (aus dem Ordner examples des RaptorXML-Applikationsordners) und erstellt ein Ausgabedokument namens summary.html. Das Ausgabedokument enthält eine Tabelle, in der die Gesamtanzahl der Aktien, die sich im Besitz der Angestellten jeder einzelnen Abteilung befinden, summiert ist.

 

Das Skript kann mit einem Befehl wie dem folgenden an die Befehlszeilenschnittstelle übergeben werden:

 

raptorxml xsi --streaming=false --script=sharesummary.py --script-api-version=1 NanonullOrg.xml

 

Anmerkung:Wenn Sie die Option --script mit dem Befehl valxml-withxsd | xsi verwenden, stellen Sie sicher, dass streaming=false definiert ist. Andernfalls wird eine Warnung zurückgegeben, dass das Skript nicht ausgeführt wurde.

 

Dateiname: sharesummary.py

 

import os

from altova import xml

 

def getElemTextValue(elem):

 """Returns the text content of an XML element"""

 

 text = ''

 for child in elem.children:

         if isinstance(child,xml.Character):

                 text += child.character_code

 return text

 

 

def getChildElemsWithName(elemParent,name):

"""Returns a list of all child elements with the given name"""

 

 elems = []

 for child in elemParent.children:

       if isinstance(child,xml.Element) and child.local_name == name:

                 elems.append(child)

 return elems

 

 

def getDepartmentName(elemDepartment):

"""Returns the name of the department specified in the <Name> element"""

 

return getElemTextValue(getChildElemsWithName(elemDepartment,'Name')[0])

 

 

def getDepartmentTotalShares(elemDepartment):

"""Returns the number of shares held by each person in that department"""

 

 # Initialize total shares to 0

 totalShares = 0

 # Sum the shares of each <Person> within the deparment

 for elemPerson in getChildElemsWithName(elemDepartment,'Person'):

elemShares = getChildElemsWithName(elemPerson,'Shares')

 # <Shares> element is optional, thus we need to check for its existence

         if len(elemShares):

 # Get the value of the <Shares> element, convert it to an integer and add it to the total sum

               totalShares += int(getElemTextValue(elemShares[0]))

 return totalShares

 

 

def calcSharesPerDepartment(instance):

"""Return a map containing the number of shares held by the persons in each department"""

 

 # Get XML root element

 elemOrgChart  = instance.document.document_element

 # Check if the root element is <OrgChart>

if not elemOrgChart or elemOrgChart.local_name != 'OrgChart' or elemOrgChart.namespace_name != 'http://www.xmlspy.com/schemas/orgchart':

         # Otherwise raise error

         raise Error('This script must be used with a valid OrgChart instance!')

 

 mapSharesPerDepartment = {}

# Go through each <Department> in each <Office> and set the number of shares held by each person in that department

for elemOffice in getChildElemsWithName(elemOrgChart,'Office'):

for elemDepartment in getChildElemsWithName(elemOffice,'Department'):

mapSharesPerDepartment[getDepartmentName(elemDepartment)] = getDepartmentTotalShares(elemDepartment)

 return mapSharesPerDepartment

 

 

def writeSummary(mapSharesPerDepartment,filename):

"""Write a summary containing the number of shares for each department to the give filename"""

 

 # Open file for writing

 f = open(filename,'w')

 f.write('<html><title>Summary</title><body><table border="1">\n')

 f.write('<tr><th>Department</th><th>Shares</th></tr>\n')

# Generate a table row for each department with the deparment's name and its total number of shares

 for name,shares in sorted(mapSharesPerDepartment.items()):

f.write('<tr><td>%s</td><td>%d</td></tr>\n'%(name,shares))

 f.write('</table></body></html>\n')

 # Close file

 f.close()

 

 

def on_xsi_valid(job,instance):

"""This method will be automatically called by RaptorXML after successful validation of the XML instance"""

 

 # Create a 'summary.html' file in the job's ouptut directory (when run from the CLI this will be the current working directory)

 filename = os.path.join(job.output_dir,'summary.html')

 # Calculate the number of shares per department and write a summary to 'summary.html'

 writeSummary(calcSharesPerDepartment(instance),filename)

 # Register the newly generated 'summary.html' output file

 job.append_output_filename(filename)

 


© 2019 Altova GmbH