Question

I'm trying to edit an existing XML document using Groovy. So far, I've got a method that looks like the following (where xmlFile is the location of the original xml file):

static String addItem(def xmlFile){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")

    StringWriter writer = new StringWriter();
    MarkupBuilder xml = new MarkupBuilder(writer);

    def rss = new XmlParser().parse(xmlFile)

    def newItem = new MarkupBuilder(writer)

    // I'm a little lost at this point.  
    // I've tried several things with no luck....



    new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile))).print(rss)

}

Here is the original XML file, which is just an RSS Feed. I'm trying to ad an item to the channel:

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<atom:link href="http://iccweb.ucdavis.edu/xml/iccrss.xml" rel="self" type="application/rss+xml" />
<title>UC Davis | Internship and Career Center | Upcoming Events</title>
<link>http://iccweb.ucdavis.edu/students/calendarevents.htm</link>
<description>Visit the ICC's web site for details on these and other upcoming events. Each quarter the ICC hosts new career and internship related career fairs, workshops, seminars, company information meetings and more!</description>
<language>en-us</language>
<lastBuildDate>Tue, 08 Apr 2014 15:50:52 -0700</lastBuildDate>
<copyright>Copyright: (C) Regents of the University of California</copyright>
<docs>http://www.ucdavis.edu/syndication/</docs>
<ttl>15</ttl>
<image>
<title>UC Davis | Internship and Career Center | Upcoming Events</title>
<url>http://iccweb.ucdavis.edu/imgs/common/ICC_logo_color-long.jpg</url>
<link>http://iccweb.ucdavis.edu/students/calendarevents.htm</link>
</image>

<item>
<guid isPermaLink="false">8450</guid>
<pubDate>Tue, 08 Apr 2014 13:10:00 -0700</pubDate>
<title>Resume Basics</title>
<description>
4/8/2014, 1:10pm-2:00pm. 229 South Hall.
Learn the essentials of how to write a resume and cover letter that get you noticed.
</description>
<link>http://iccweb.ucdavis.edu/students/calendarevents.htm?d=4/8/2014</link>
</item>
</channel>
</rss>
Was it helpful?

Solution

You can try:

def rss = new XmlParser().parse(xmlFile)
rss.channel + {
   item {
     guid(isPermaLink: "false", "8451")
   } 
}
//and so on...
println xml

Have a look at this manual and this API docs. Feel free to ask further questions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top