Question

need an xsl that will remove empty tags and attributes from an xml.

Asked by: cjferris

Hello

I would like help in creating an xsl (and to flatten out the learning curve). I’m new to using xsl, but have good experience with dom trees and xml. Using xsl looks like it can do many things I have been coding manually.  What I need now is to take a xml doc and remove all attributes and empty tags. (I consider empty tags as tag without any data).  To help illustrate this, below is a sample of the input/source xml and the resulting xml.

xml source

<Sales_ticket>
    <Sales_ticket_header>
      <Sales_ticket_header_Transmit_version/>
      <Sales_ticket_header_Store_number/>
      <Sales_ticket_header_Register_ID/>
      <Sales_ticket_header_Transaction_date/>
      <Sales_ticket_header_Transaction_time/>
      <Sales_ticket_header_Polled_date ref="XDT50">11232005</Sales_ticket_header_Polled_date>
      <Sales_ticket_header_Ticket_number ref="X50TICK">36154</Sales_ticket_header_Ticket_number>
      <Sales_ticket_header_Receptionist_ID ref="X50RECP">00</Sales_ticket_header_Receptionist_ID>
      <Sales_ticket_header_Employee_ID ref="X50EMPN">05</Sales_ticket_header_Employee_ID>
      <Sales_ticket_header_Customer_type ref="X50CTYP">4</Sales_ticket_header_Customer_type>
      <Sales_ticket_header_price_group ref="X50PGRP">020</Sales_ticket_header_price_group>
      <Sales_ticket_header_POS_sales_tax ref="X50STAX">000000.00</Sales_ticket_header_POS_sales_tax>
    </Sales_ticket_header>  
    <Sales_ticket_detail>
      <Sales_ticket_detail_Ticket_number ref="X51TICK">36154</Sales_ticket_detail_Ticket_number>
      <Sales_ticket_detail_Employee_ID ref="X51EMPN">05</Sales_ticket_detail_Employee_ID>
      <Sales_ticket_detail_Detail_price_group ref="X51PGRP">020</Sales_ticket_detail_Detail_price_group>
      <Sales_ticket_detail_Retail_or_service_flag ref="X51TYPE">S</Sales_ticket_detail_Retail_or_service_flag>
      <Sales_ticket_detail_Retail_or_service_number ref="X51COD1">00865</Sales_ticket_detail_Retail_or_service_number>
      <Sales_ticket_detail_Subservice_number ref="X51COD2">000</Sales_ticket_detail_Subservice_number>
      <Sales_ticket_detail_List_price ref="X51LPRC">000012.50</Sales_ticket_detail_List_price>
      <Sales_ticket_detail_Quantity_sold ref="X51QTYS">01</Sales_ticket_detail_Quantity_sold>
      <Sales_ticket_detail_Item_taxed ref="NG51ITAX">N</Sales_ticket_detail_Item_taxed>
    </Sales_ticket_detail>
    <Payment_detail>
      <Payment_detail_Ticket_number ref="X54TICK">36154</Payment_detail_Ticket_number>
      <Payment_detail_Payment_type ref="X54TYPE">1</Payment_detail_Payment_type>
      <Payment_detail_Amount_tendered ref="X54AMNT">0000000000050.00</Payment_detail_Amount_tendered>
      <Payment_detail_Amount_negative ref="NG54NEGA">N</Payment_detail_Amount_negative>
      <Payment_detail_Gift_certificate_number_redeemed ref="X54GCRD">000000000</Payment_detail_Gift_certificate_number_redeemed>
      <Payment_detail_Change_record ref="NG54CHNG">N</Payment_detail_Change_record>
      <Payment_detail_Change_amount ref="NG54CAMT">0000000000000.00</Payment_detail_Change_amount>
      <Credit_card_detail>
           <Credit_card_detail_Ticket_number ref="NG55TICK"/>
           <Credit_card_detail_Charge_amount ref="NG55CHGA"/>
      </Credit_card_detail>
     </Payment_detail>
</Sales_ticket>

desired xml result

<Sales_ticket>
    <Sales_ticket_header>
      <Sales_ticket_header_Polled_date>11232005</Sales_ticket_header_Polled_date>
      <Sales_ticket_header_Ticket_number>36154</Sales_ticket_header_Ticket_number>
      <Sales_ticket_header_Employee_ID>05</Sales_ticket_header_Employee_ID>
      <Sales_ticket_header_Customer_type>4</Sales_ticket_header_Customer_type>
      <Sales_ticket_header_price_group>020</Sales_ticket_header_price_group>
      <Sales_ticket_header_POS_sales_tax>000000.00</Sales_ticket_header_POS_sales_tax>
    </Sales_ticket_header>  
    <Sales_ticket_detail>
      <Sales_ticket_detail_Ticket_number>36154</Sales_ticket_detail_Ticket_number>
      <Sales_ticket_detail_Employee_ID>05</Sales_ticket_detail_Employee_ID>
      <Sales_ticket_detail_Detail_price_group>020</Sales_ticket_detail_Detail_price_group>
      <Sales_ticket_detail_service_flag>S</Sales_ticket_detail_service_flag>
      <Sales_ticket_detail_service_number>00865</Sales_ticket_detail_service_number>
      <Sales_ticket_detail_Subservice_number>000</Sales_ticket_detail_Subservice_number>
      <Sales_ticket_detail_List_price>000012.50</Sales_ticket_detail_List_price>
      <Sales_ticket_detail_Quantity_sold>01</Sales_ticket_detail_Quantity_sold>
      <Sales_ticket_detail_Item_taxed>N</Sales_ticket_detail_Item_taxed>
    </Sales_ticket_detail>
    <Payment_detail>
      <Payment_detail_Ticket_number>36154</Payment_detail_Ticket_number>
      <Payment_detail_Payment_type>1</Payment_detail_Payment_type>
      <Payment_detail_Amount_tendered>000000050.00</Payment_detail_Amount_tendered>
      <Payment_detail_Amount_negative>N</Payment_detail_Amount_negative>
      <Payment_detail_Gift_certificate_number_redeemed>000</Payment_detail_Gift_certificate_number_redeemed>
      <Payment_detail_Change_record>N</Payment_detail_Change_record>
      <Payment_detail_Change_amount>00000000.00</Payment_detail_Change_amount>
     </Payment_detail>
</Sales_ticket>

Basically I’m trying to reduce the document size before sending it on its way.

Here is what I got so far, it seems to just remove the attributes, but not the empty tags. Not sure what tells it to remove the attributes either.  So 500 points for one that does both, with comments telling what part does what.  Thanks.

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" omit-xml-declaration="no"/>
<xsl:template match="* | /">
    <xsl:copy>
        <xsl:apply-templates/>
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-11-29 at 09:07:04ID21646666
Tags

empty

,

remove

,

xsl

,

xml

,

tags

Topics

Extensible Markup Language (XML)

,

Extensible HTML (XHTML)

Participating Experts
2
Points
500
Comments
9

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. xsl
    Hi, I'm just starting to play with xsl, could someone please place comments in the script below on as many lines as possible so I can figure this thing out and go from there... For example the resulting page has more link in it that points to the document from rss feed, simp...
  2. XSL adding xmlns="" automatically
    I am a relative notice to XSL - I am using XSL to produce XHTML pages. I have a problem where the XSL is adding xmlns="" to HTML nodes in my XSL. I have two files I will show you the head of each because i think this is effecting whats happening page.xsl - <...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: metalmickeyPosted on 2005-11-29 at 09:33:34ID: 15381780

could you test the string length of all children of sales ticket?

<xsl:template match="Sales_ticket/*">
<xsl:if test ="string-length(., !=0)">
   <xsl:copy>
       <xsl:apply-templates/>
   </xsl:copy>
</xsl:template>

MM

 

by: GertonePosted on 2005-11-29 at 10:40:47ID: 15382342

Hi cjferris,

have a look at this question,
http://www.experts-exchange.com/Web/Web_Languages/XML/Q_21484858.html
At the end it has an XSLT that strips all the empty elements,
but also its parents if they become empty because of the removal

If you remove the template for attributes, it does what you need


Cheers!

 

by: GertonePosted on 2005-11-29 at 11:06:09ID: 15382533

cjferris,

sorry MetalMickey, didn't realise you already answered.
Your solution will not tackle elements deeper in the hierarchy, eg. children of Payment_Detail
but you are right about the test
you can of course do the test in the apply templates

Here is the solution from the above mentioned question,
adapted to remove attributes as well

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
    <xsl:template
        match="node()[descendant-or-self::*[string-length(normalize-space(.)) &gt; 0]]">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates select="node()"/>
        </xsl:copy>    
    </xsl:template>
    <xsl:template match="text()">
        <xsl:value-of select="."/>
    </xsl:template>
    <xsl:template match="@*"/>
 </xsl:stylesheet>

Here is how it works
There are three templates
- match='text()' copies the value of every text node
- match='@*' is an empty template for every attribute (@* is the attribute wildcard) no operation so deleted
- match="node()[descendant-or-self::*[string-length(normalize-space(.)) &gt; 0]]"
is a template for every element that either has some text itself, or a descendent with some text content
    - [] is a predicate, so it restricts the node
    - descendant-or-self::* is the self node or a descendant, wildcard for the node-name
    - new [] predicate stringlength of that element (after space normalisation) more than zero
        (this means <a>      </a> would be removed too, if that is not OK, remove the normalize-space function))

inside this template, there is a <xsl:copy> copying the tags, an apply-template for all the attributes (could be left out, I just made the attribute processing explicit, because you wanted to know) I do apply templates for the attributes and then explicitely do nothing with them for showing you
and then I apply templates the node

hope this is clear enough

for an XSLT tutorial, see www.w3schools.com/XSLT

cheers

 

by: GertonePosted on 2005-11-29 at 11:06:56ID: 15382538

correct URLs are a blessing :-)
http://www.w3schools.com/xsl/default.asp

 

by: cjferrisPosted on 2005-11-30 at 08:00:14ID: 15389120

Very close

Metalmickey solution didn't work, It threw the following exception:

javax.xml.transform.TransformerException: A location path was expected, but the following token was encountered:  !

Gertones works but adds, leaves blank lines where the empty tags where removed. For example:

<?xml version="1.0" encoding="UTF-8"?>
<root>

<Sales_ticket>
    <Sales_ticket_header>
   
   
   
   
   
    <Sales_ticket_header_Polled_date>11232005</Sales_ticket_header_Polled_date>
    <Sales_ticket_header_Ticket_number>36154</Sales_ticket_header_Ticket_number>
    <Sales_ticket_header_Receptionist_ID>00</Sales_ticket_header_Receptionist_ID>


I pass the resulting DOM document to my DOMTreeWalker and you can see there remains a text node at these blank lines.  How can these be removed?  

Getones solution did technically meet my requirements since the tags are removed. I failed to specify to also to remove the text nodes with the empty tags.  So I will accept this answer, plus he explained how it worked like I asked.  

Getones, I would appreciate a follow up with the template showing how to remove these text nodes.

Thanks.




 

by: GertonePosted on 2005-11-30 at 08:08:33ID: 15389198

There is one line you should add,
stripping the spaces in all affected higher level elements

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:strip-space elements="Sales_ticket Sales_ticket_header Sales_ticket_detail Payment_detail Credit_card_detail"/>
    <xsl:output method="xml" encoding="UTF-8" indent="yes"/>
...

does the job for me

 

by: cjferrisPosted on 2005-11-30 at 09:02:11ID: 15389708

That worked.  But the doc is no longer indented.

One thing I found out digging into the DOM tree and the xml is that the text nodes are created from the CR/LF at the end of each line in the xml document.  I deleted these in the doc (making it unreadable and thus not a solution) and that worked too.

Your follow up above works, but that is hardcoding for that particular xml.  We will have almost a 100 different xml coming through for each service we have, Sales_ticket is just one of those services.

thanks

 

by: cjferrisPosted on 2005-11-30 at 09:45:43ID: 15390091

Last comment, total solution found.  

adding  <xsl:strip-space elements="*"/>

and then making the xml look pretty again by switching indenting on on the format of the
serializer does the trick.  Case closed

    // Serialize DOM tree
    OutputFormat    format  = new OutputFormat(doc);
    format.setIndenting(true);

Thanks all.


 

by: GertonePosted on 2005-11-30 at 10:34:24ID: 15390447

you are welcome

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...