使用Groovy编辑现有XML文档

时间:2014-04-09 18:34:05

标签: xml groovy rss

我正在尝试使用Groovy编辑现有的XML文档。到目前为止,我有一个类似于以下的方法(其中xmlFile是原始xml文件的位置):

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)

}

这是原始的XML文件,它只是一个RSS Feed。我正在尝试向频道投放一个项目:

<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>

1 个答案:

答案 0 :(得分:1)

您可以尝试:

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

查看this手册和this API文档。随意提出进一步的问题。