Sponsored Content
Top Forums Shell Programming and Scripting Replacing the last record in xml with different tags Post 302436178 by fpmurphy on Friday 9th of July 2010 12:16:31 PM
Old 07-09-2010
You can also use an XSLT stylesheet to transform your document
Code:
<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="2.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:output method="xml" indent="yes"/>

   <xsl:template match="*">
       <xsl:copy><xsl:apply-templates /></xsl:copy>
   </xsl:template>

   <xsl:template match="RevenueAmounts[position() = last()]">
    <xsl:variable name="count" select="count(//RevenueAmounts) - 1"/>
    <xsl:text>     </xsl:text><ReportTrailer><xsl:text>
         </xsl:text><RevenueAmounts_total element_total="{$count}"><xsl:text>
             </xsl:text><GrossAccount_total><xsl:text>
                  </xsl:text><Credit><xsl:value-of select="./GrossAccount/Credit"/></Credit><xsl:text>
                  </xsl:text><Debit><xsl:value-of select="./GrossAccount/Debit"/></Debit><xsl:text>
              </xsl:text></GrossAccount_total><xsl:text>
              </xsl:text><DiscountAccount_total><xsl:text>
                  </xsl:text><Credit><xsl:value-of select="./DiscountAccount/Credit"/></Credit><xsl:text>
                  </xsl:text><Debit><xsl:value-of select="./DiscountAccount/Debit"/></Debit><xsl:text>
              </xsl:text></DiscountAccount_total><xsl:text>
              </xsl:text><NetAccount_total><xsl:text>
                  </xsl:text><Credit><xsl:value-of select="./NetAccount/Credit"/></Credit><xsl:text>
                  </xsl:text><Debit><xsl:value-of select="./NetAccount/Debit"/></Debit><xsl:text>
              </xsl:text></NetAccount_total><xsl:text>
         </xsl:text></RevenueAmounts_total><xsl:text>
    </xsl:text></ReportTrailer>
   </xsl:template>

</xsl:stylesheet>

All the <xsl:text> elements are in the stylesheet to output white-space in the resultant document. Remember an XSL processor is not a formatting engine. If layout is not an issue, just remove them.

The stylesheet can handle any number of RevenueAmount nodes with the last RevenueAmount node being converted to a ReportTrailer node.
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

replacing string in an XML file

Hi all, I need to replace string in XML file..XML file like <dependency> <groupId>fr.orange.portail.ear</groupId> <artifactId>_AdminServicesEAR</artifactId> <version>1.0.0-20080521.085352-1</version> <type>ear</type> </dependency> <dependency> ... (2 Replies)
Discussion started by: subin_bala
2 Replies

2. UNIX for Advanced & Expert Users

How to read an Xml record contained in a file--urgent

Hi I have an xml file which has multiple xml records.. I don't know how to read those records and pipe them to another shell command the file is like <abc>z<def>y<ghi>x........</ghi></def></abc> (1st record) <jkl>z<mno>y<pqr>x........</pqr></mno></jkl> (2nd record) Each record end... (4 Replies)
Discussion started by: aixjadoo
4 Replies

3. Shell Programming and Scripting

Replacing number between xml tags with ksh shell script

Hallo, im basically a complete noob on shell scripting and im trying to replace or rather add 1 to a number between xml tags. The xml basically has a tag somewhere that looks like this: <tag>12345678901234</tag> Now i want to replace the number between the tags. And i want the file to... (6 Replies)
Discussion started by: Demoric
6 Replies

4. Shell Programming and Scripting

Replacing part of XML code inside comment tags

Hello! I'd like to modify custom values in a XML config file between comment tags using bash script. <feature> <keyboardshortcut>C-m</keyboardshortcut> <option1>disabled</option2> <option2>enabled</option2> </feature> <!-- bash script features START --> <feature> ... (2 Replies)
Discussion started by: prism1
2 Replies

5. Shell Programming and Scripting

Reading XML and replacing a string

Hi All, My thanks in advance for you guys reading this and for any posts. I'm having 100 XML files, I need script which replace a specific string. It must be incrementing in 100 xml files.. Sample XML files: <hwIPHostName type="attrib">DEMO1</hwIPHostName> I need Demo1 to be... (4 Replies)
Discussion started by: karty2129
4 Replies

6. Shell Programming and Scripting

How to add the multiple lines of xml tags before a particular xml tag in a file

Hi All, I'm stuck with adding multiple lines(irrespective of line number) to a file before a particular xml tag. Please help me. <A>testing_Location</A> <value>LA</value> <zone>US</zone> <B>Region</B> <value>Russia</value> <zone>Washington</zone> <C>Country</C>... (0 Replies)
Discussion started by: mjavalkar
0 Replies

7. Shell Programming and Scripting

Shell Command to compare two xml lines while ignoring xml tags

I've got two different files and want to compare them. File 1 : HTML Code: <response ticketId="944" type="getQueryResults"><status>COMPLETE</status><description>Query results fetched successfully</description><recordSet totalCount="1" type="sms_records"><record... (1 Reply)
Discussion started by: Shaishav Shah
1 Replies

8. Shell Programming and Scripting

Replacing a value in all xml's

Hi Folks, Could you please advise what will be the unix command to replace the character in all xml's under a particular directory for example let say I rite now at the following below location $ cd /opt/apr/rt/conf now under conf there are so many xml's and in those xml's i want to... (2 Replies)
Discussion started by: punpun66
2 Replies

9. Shell Programming and Scripting

Extract timestamp from first record in xml file and it checks if not it will replace first record

I have test.xml <emp><id>101</id><name>AAA</name><date>06/06/14 1811</date></emp> <Join><id>101</id><city>london</city><date>06/06/14 2011</date></join> <Join><id>101</id><city>new york</city><date>06/06/14 1811</date></join> <Join><id>101</id><city>sydney</city><date>06/06/14... (2 Replies)
Discussion started by: vsraju
2 Replies

10. Shell Programming and Scripting

Replacing tab value in xml file

Hi I am working on xml file. I have to make sure below lines containing values within quotes are replaced by some character like "-". Below are different lines in xml file. Pattern 1: <Connector port=.... ..... keystoremyPass="xxx" /> Pattern 2: myword="xxxxx" ... (11 Replies)
Discussion started by: krsnadasa
11 Replies
TclXSLT(3tcl)															     TclXSLT(3tcl)

NAME
TclXSLT - XSLT support for Tcl SYNOPSIS
package require xslt ::xslt::compile doc ssheet method ? option value ... ? ? args ... ? ::xslt::extensionadd nsuri tcl-namespace ::xslt::securityrequest detail DESCRIPTION
TclXSLT is a wrapper for the Gnome libxslt library that allows an application to perform XSL transformations (XSLT). The package also pro- vides a binding to the XSLT extension mechanism so that XSLT extension may be implemented using Tcl scripts. Transformation only works with documents created by TclDOM/libxml2. The TclXSLT package makes extensive use of Tcl objects. Compiled XSL stylesheets are stored as the internal representation of a Tcl object. Source and result documents are accessed via TclDOM's C interface as Tcl objects. This allows the application to cache parsed XML documents and compiled XSL stylesheets for better runtime performance. PACKAGES AND NAMESPACES
The TclXSLT package defines the xslt package and also a Tcl namespace using that name. COMMANDS
::xslt::compile The ::xslt::compile command compiles a stylesheet document. It returns a compiled stylesheet object and also defines a Tcl command to access the stylesheet. This Tcl command may be used to transform XML documents. Example.PP set source_doc [::dom::libxml2::parse $XML] set ssheet_doc [::dom::libxml2::parse $XSLstylesheet] set ssheet [::xslt::compile $ssheet_doc] set result [$ssheet transform $source_doc] NB. It is advisable to use the -baseuri option when parsing the source and stylesheet documents to allow external resources to be resolved. Stylesheet Command The stylesheet command created by ::xslt::compile command accesses a compiled stylesheet. Command Methods The following command methods may be used: cget option Returns the value of an option. See below for the list of valid options. configure optionvalue Sets the value of an option. Available options are as follows: -indent Specifies whether the output being produced by the stylesheet should be idented (or "pretty-printed"). This is usually set by the styesheet's xsl:output element. The result is a boolean value. This is a read-only option. -messagecommand script This option specifies a Tcl command to be evaluated when a message is produced by the stylesheet. Messages may be produced when the stylesheet detects an error during processing, or when the stylesheet uses the xsl:message element. It is currently not possible to distinguish between an error message and a message produced using xsl:message. -method Specifies the output being produced by the stylesheet. This is usually set by the styesheet's xsl:output element. May have the value xml, html, xhtml, text or an empty string. If the result is an empty string, then the output method used depends on the type of the result document. If the result doc- ument is of type "HTML" (ie. if [dom::node cget $resultdoc -nodeType] returns HTMLdocument), then the html output method should be used. Otherwise the output method to use is xml. This is a read-only option. -profilechannel Specifies the name of a channel into which profiling information is written. The channel must have been opened for writing, or an error will be returned when attempting a transformation. Only file channels may be used and only on Unix systems. -resulturi Specifies the target URI for the transformation, ie. where the result will be written to. The result document is not written to this URI automatically; the application should write the result document to this URI itself. Some transformation constructs resolve relative URIs against this URI. For example, a subsidiary result document produced using the document element. get what Returns information from the stylesheet. The following values may be used for what: parameters Returns a Tcl list describing the parameters that the stylesheet accepts. Each member of the list is itself a Tcl list with three members: {name ns select}. name is the name of the parameter, ns is the XML namespace for the parameter and select is the value of the select attribute of the param element, if any (ie. the default value of the parameter). This implementation is not able to return a default value set using the content of the param element. All stylesheet parameters are returned by this method, including those in included/imported stylesheets. Where more than one parameter is defined with the same name, only the parameter with the highest import precedence is included in the returned list. transform source name value Performs an XSL transformation on the given source document. Stylesheet parameters may be specified as name-value pairs. The return result is the DOM token for the result document. Stylesheet Parameters Any number of name-value pairs may be specified as arguments to the stylesheet transform method. These are passed as values for parameters in the stylesheet. libxslt interprets the values as XPath expressions, where the context node is the root node for the source document. To pass a value as a string it must be XPath-quoted, for example set library "Gnome libxslt" $ssheet transform $source_doc library '$library' author "'Daniel Veillard'" node {/*/Element[3]} Following is an example of how to use the stylesheet transform method. Example.PP set source_doc [::dom::libxml2::parse $XML] set ssheet_doc [::dom::libxml2::parse $XSLstylesheet] set ssheet [::xslt::compile $ssheet_doc] set result_doc [$ssheet transform $source_doc] set result_xml [::dom::libxml2::serialize $result_doc -method [$ssheet cget -method]] ::xslt::extension The ::xslt::extension command is used to manage extensions of the libxslt library. The add is used to register an extension. The remove is used to unregister an extension. See EXTENSIONS for more detail. ::xslt::security The ::xslt::security command is a "call-in" used to manage the security of a stylesheet performing a transformation. The TclXSLT package does not create this command. A stylesheet may need to perform an operation on an external resource, such as reading or writing a file, or opening a network connection. Before performing such an operation, TclXSLT will invoke the ::xslt::security command. It interprets the result of the command as a boolean value, and only if the "true" value is returned will it instruct the libxslt library to continue. TclXSLT will invoke the ::xslt::security command in a different fashion depending on whether the current interpreter is safe or unsafe. * If the current interpeter is unsafe (ie. it is a trusted interpreter) then the command is invoked in the usual manner (see below for arguments). If the command does not exist then the value "true" is the default, ie. the operation will be permitted. * If the current interpreter is safe then the command is invoked as a hidden command. This is to ensure that the untrusted script cannot intercept the invocation of the command. If the hidden command does not exist then the value "false" is the default, ie. the operation will not be permitted. When the ::xslt::security command is invoked two arguments are appended: ::xslt::securityrequest detail request This indicates the operation being requested and may have one of the following values: * readfile * * * * EXTENSIONS
The TclXSLT package allows an application to bind Tcl scripts to the extension mechanism of libxslt. This means that Tcl scripts may pro- vide the implementation of an XSLT extension element or function. The binding is achieved to associating a Tcl namespace with an XML namespace. Implementing An Extension The Tcl application uses the ::xslt::extension add command to register an extension. An XML Namespace for the extension is specified as an argument, along with a Tcl namespace that will provide implementations of extension elements and functions. For example, ::xslt::extension add http://tclxml.sourceforge.net/Example ::example Everytime the ::xslt::transform command is executed, a newly-created XSLT engine is initialized. For each registered extension, every pro- cedure in the associated Tcl namespace is defined in the XSLT engine as either an extension element or an extension function. The proce- dure is defined as an extension function if it has a variable argument list, otherwise it is defined as an extension element. The proce- dure name is used as the local part of the extension name. For example, namespace eval example { namespace export myfunc myelement } proc example::myfunc {name args} { global app return $app($name) } proc example::myelement {content node inst avts} { global app puts $app([dom::libxml2::node cget $node -nodeName]) return {} } "myfunc" is defined as an extension function and "myelement" is defined as an extension element. Extension Functions The arguments to an extension function are passed as parameters to the Tcl procedure. Each argument may be passed as a string or as a node- set. Nodesets are presented as TclDOM nodes. The return result of the Tcl procedure becomes the return value of the extension function. The type of the result is preserved where pos- sible, otherwise it is converted to a string value. Extension Elements When an extension element associated with a registered namespace is instantiated all attributes of the extension element are evaluated as Attribute Value Templates and the content of the extension element is evaluated as a sequence constructor. The Tcl procedure associated with the extension element is then invoked. The Tcl procedure is passed four parameters: * The first parameter is a DOM document, an RVT, that is the result of the sequence constructor. * The second parameter is the current node in the source document. * The third parameter is the extension element in the stylesheet document. * The fourth parameter is a list. Each element in the list represents an attribute of the extension element. The list elements are each a sublist that has three values: * Attribute name * Attribute XML namespace * Attribute value after evaluation as an AVT Any result returned by the Tcl procedure is discarded (in the current implementation). If the Tcl procedure raises an error then this is passed through to the XSL stylesheet as an XSLT exception condition. Using An Extension To invoke an extension in an XSL stylesheet, use the normal XSLT extension mechanism. The XML Namespace matches the extension to the reg- istered Tcl namespace (NB. the stylesheet author is free to choose any prefix for the extension namespace). For example, <xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:eg='http://tclxml.sourceforge.net/Example'> <xsl:template match='/'> <xsl:text>Result of calling extension is "</xsl:text> <xsl:value-of select='eg:myfunc("foo")'/> <xsl:text>". </xsl:text> </xsl:template> </xsl:stylesheet> This stylesheet would result in the following Tcl script being evaluated: ::example::myfunc foo TclXML Package Commands TclXML TclXSLT(3tcl)
All times are GMT -4. The time now is 09:06 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy