DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert XLS to XLSX in Java
  • Thread-Safety Pitfalls in XML Processing
  • Loading XML into MongoDB
  • SmartXML: An Alternative to XPath for Complex XML Files

Trending

  • Emerging Data Architectures: The Future of Data Management
  • *You* Can Shape Trend Reports: Join DZone's Software Supply Chain Security Research
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Accelerating AI Inference With TensorRT
  1. DZone
  2. Coding
  3. Languages
  4. Writing Groovy's groovy.util.Node (XmlParser) Content as XML

Writing Groovy's groovy.util.Node (XmlParser) Content as XML

By 
Dustin Marx user avatar
Dustin Marx
·
Feb. 20, 15 · Interview
Likes (6)
Comment
Save
Tweet
Share
22.0K Views

Join the DZone community and get the full member experience.

Join For Free

Groovy's XmlParser makes it easy to parse an XML file, XML input stream, or XML string using one its overloaded parse methods (or parseText in the case of the String). The XML content parsed with any of these methods is made available as a groovy.util.Node instance. This blog post describes how to make the return trip and write the content of the Node back to XML in alternative formats such as a File or aString.

Groovy's MarkupBuilder provides a convenient approach for generating XML from Groovy code. For example, I demonstrated writing XML based on SQL query results in the post GroovySql and MarkupBuilder: SQL-to-XML. However, when one wishes to write/serialize XML from a Groovy Node, an easy and appropriate approach is to use XmlNodePrinter as demonstrated in Updating XML with XmlParser.

The next code listing, parseAndPrintXml.groovy demonstrates use of XmlParser to parse XML from a provided file and use of XmlNodePrinter to write that Node parsed from the file to standard output as XML.

parseAndPrintXml.groovy : Writing XML to Standard Output

#!/usr/bin/env groovy

// parseAndPrintXml.groovy
//
// Uses Groovy's XmlParser to parse provided XML file and uses Groovy's
// XmlNodePrinter to print the contents of the Node parsed from the XML with
// XmlParser to standard output.

if (args.length < 1)
{
   println "USAGE: groovy parseAndPrintXml.groovy <XMLFile>"
   System.exit(-1)
}

XmlParser xmlParser = new XmlParser()
Node xml = xmlParser.parse(new File(args[0]))
XmlNodePrinter nodePrinter = new XmlNodePrinter(preserveWhitespace:true)
nodePrinter.print(xml)

Putting aside the comments and code for checking command line arguments, there are really 4 lines (lines 15-18) in the above code listing of significance to this discussion. These four lines demonstrate instantiating anXmlParser (line 15), using the instance of XmlParser to "parse" a File instance based on a provided argument file name (line 16), instantiating an XmlNodePrinter (line 17), and using that XmlNodePrinterinstance to "print" the parsed XML to standard output (line 18).

Although writing XML to standard output can be useful for a user to review or to redirect output to another script or tool, there are times when it is more useful to have access to the parsed XML as a String. The next code listing is just a bit more involved than the last one and demonstrates use of XmlNodePrinter to write the parsed XML contained in an Node instance as a Java String.

parseXmlToString.groovy : Writing XML to Java String

#!/usr/bin/env groovy

// parseXmlToString.groovy
//
// Uses Groovy's XmlParser to parse provided XML file and uses Groovy's
// XmlNodePrinter to write the contents of the Node parsed from the XML with
// XmlParser into a Java String.

if (args.length < 1)
{
   println "USAGE: groovy parseXmlToString.groovy <XMLFile>"
   System.exit(-1)
}

XmlParser xmlParser = new XmlParser()
Node xml = xmlParser.parse(new File(args[0]))
StringWriter stringWriter = new StringWriter()
XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(stringWriter))
nodePrinter.setPreserveWhitespace(true)
nodePrinter.print(xml)
String xmlString = stringWriter.toString()
println "XML as String:\n${xmlString}"

As the just-shown code listing demonstrates, one can instantiate an instance of XmlNodePrinter that writes to a PrintWriter that was instantiated with a StringWriter. This StringWriter ultimately makes the XML available as a Java String.

Writing XML from a groovy.util.Node to a File is very similar to writing it to a String with a FileWriterused instead of a StringWriter. This is demonstrated in the next code listing.

parseAndSaveXml.groovy : Write XML to File

#!/usr/bin/env groovy

// parseAndSaveXml.groovy
//
// Uses Groovy's XmlParser to parse provided XML file and uses Groovy's
// XmlNodePrinter to write the contents of the Node parsed from the XML with
// XmlParser to file with provided name.

if (args.length < 2)
{
   println "USAGE: groovy parseAndSaveXml.groovy <sourceXMLFile> <targetXMLFile>"
   System.exit(-1)
}

XmlParser xmlParser = new XmlParser()
Node xml = xmlParser.parse(new File(args[0]))
FileWriter fileWriter = new FileWriter(args[1])
XmlNodePrinter nodePrinter = new XmlNodePrinter(new PrintWriter(fileWriter))
nodePrinter.setPreserveWhitespace(true)
nodePrinter.print(xml)

I don't show it in this post, but the value of being able to write a Node back out as XML often comes after modifying that Node instance. Updating XML with XmlParser demonstrates the type of functionality that can be performed on a Node before serializing the modified instance back out.


XML Groovy (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert XLS to XLSX in Java
  • Thread-Safety Pitfalls in XML Processing
  • Loading XML into MongoDB
  • SmartXML: An Alternative to XPath for Complex XML Files

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!