Skriptcode

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

Startseite > 

Skriptcode

Das folgende mit Anmerkungen versehene Python-Skript (reformat.py) formatiert die XML-Datei NanonullOrg.xml (aus dem Ordner examples des RaptorXML-Applikationsordners). Jedes Element wird mit Tabulatoren eingerückt und jedes Attribut wird in eine separate Zeile gesetzt (wodurch der Vergleich mit einem Vergleichstool übersichtlicher wird). Das Ausgabedokument hat den Namen output.xml.

 

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

 

 

raptorxmlxbrl xsi --streaming=false --script=reformat.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: reformat.py

 

import os

from altova import xml, xsd

 

def writeCharacter(f,char,depth):

"""Output XML for the charater node"""

 

 # Ignore text nodes containing only whitespace characters

 if not char.element_content_whitespace:

         # Write the text content

         f.write("\t"*depth + char.character_code+'\n')

 

 

def writeComment(f,comment,depth):

 """Output XML for the comment node"""

 

 # Write the comment

f.write("\t"*depth + '<!-- '+comment.content+'-->\n')

 

 

def writeAttribute(f,attr,depth):

 """Output XML for the attribute node (on a separate line)"""

 
# Look up prefix for the namespace in the inscope namespace map
prefix = None
if attr.namespace_name:

         inscope = {}

 for namespace in attr.owner_element.inscope_namespaces:

               inscope[namespace.namespace_name] = namespace.prefix

 prefix = inscope[attr.namespace_name]

         if prefix:

                 prefix += ':'        

 if not prefix:

         prefix = ''

 

# Write the attribute with its value

f.write("\t"*depth + "@"+prefix+attr.local_name+"=\""+attr.normalized_value+"\"\n")

 

 

def writeNSAttribute(f,attr,depth):

"""Output XML for the namespace attribute node (on a separate line)"""

 

 prefix = ""

 if attr.local_name != 'xmlns':

         prefix = 'xmlns:'

 

# Write the namespace attribute with its value

f.write("\t"*depth + "@"+prefix+attr.local_name+"=\""+attr.normalized_value+"\"\n")

 

 

def writeChildren(f,elem,depth):

 """Output XML for all the child nodes (indented by the given depth)"""

 

 # Iterate over all child nodes

 for child in elem.children:

         if isinstance(child,xml.Element):

                 writeElement(f,child,depth)

         elif isinstance(child,xml.Comment):

                 writeComment(f,child,depth)

         elif isinstance(child,xml.Character):

                 writeCharacter(f,child,depth)

 

 

def writeElement(f,elem,depth):

"""Output XML for the element node with all its child nodes (indented by the given depth)"""

 

# Look up prefix for the namespace in the inscope namespace map

 prefix = None

 if elem.namespace_name:

         inscope = {}

         for namespace in elem.inscope_namespaces:

inscope[namespace.namespace_name] = namespace.prefix

         prefix = inscope[elem.namespace_name]

         if prefix:

                 prefix += ':'

 if not prefix:

         prefix = ''

 

if len(list(elem.attributes)) + len(list(elem.namespace_attributes)) == 0:

 # Write complete start tag (without attributes)

 f.write("\t"*depth + "<"+prefix+elem.local_name+'>\n')

 else:

# Write start tag without the closing '>'

f.write("\t"*depth + "<"+prefix+elem.local_name+'\n')

 

# Write namespace attributes on separate lines

for attr in elem.namespace_attributes:

writeNSAttribute(f,attr,depth+1)

# Write attributes on separate lines

for attr in elem.attributes:

writeAttribute(f,attr,depth+1)

# Close the start tag

f.write("\t"*depth + ">\n")

 

 # Write all element's children

 writeChildren(f,elem,depth+1)

 

 # Write end tag

f.write("\t"*depth + "</"+prefix+elem.local_name+">\n")

 

 

def writeInstance(instance,filename):

"""Ouptput XML for the given instance where each element is indented by tabs and each attribute is placed on a separate line"""

 

# Open output file

f = open(filename,'w')

# Write the content of the XML instance document

writeChildren(f,instance.document,0)

# Close output 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 'output.xml' 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,'output.xml')

# Write a reformatted version of the instance XML file where each attribute is placed on a separate line

writeInstance(instance,filename)

# Register the newly generated 'output.xml' output file

job.append_output_filename(filename)

 


© 2019 Altova GmbH