比较groovy/java解析xml文件

2012-11-12

  xml内容:

  <emails>

  <email id=’1′>

  <subject>hello world</subject>

  <sender>test@163.com</sender>

  <receivedDate>2010-11-01 10:10:30</receivedDate>

  </email>

  <email id=’2′>

  <subject>hello world demo 2</subject>

  <sender>test@2163.com</sender>

  <receivedDate>2010-11-02 10:10:30</receivedDate>

  </email>

  <email id=’3′>

  <subject>hello world demo 3</subject>

  <sender>test3@163.com</sender>

  <receivedDate>2010-11-03 10:10:30</receivedDate>

  </email>

  </emails>

  java解析实现:

  import org.w3c.dom.Document;

  import org.w3c.dom.Node;

  import org.w3c.dom.NodeList;

  import org.xml.sax.SAXException;

  import javax.xml.parsers.DocumentBuilder;

  import javax.xml.parsers.DocumentBuilderFactory;

  import javax.xml.parsers.ParserConfigurationException;

  import java.io.IOException;

  import java.io.InputStream;

  public class EmailsDemo {

  public static void main(String[] args)

  {

  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

  try {

  DocumentBuilder builder = factory.newDocumentBuilder();

  InputStream is = EmailsDemo.class.getResourceAsStream(“./emails.xml”);

  Document document = builder.parse(is);

  NodeList nodes = document.getElementsByTagName(“email”);

  for (int i = 0; i < nodes.getLength(); i++)

  {

  Node node = nodes.item(i);

  Node id = node.getAttributes().getNamedItem(“id”);

  System.out.println(“id = ” + id.getTextContent());

  }

  } catch (ParserConfigurationException e) {

  e.printStackTrace();

  } catch (SAXException e) {

  e.printStackTrace();

  } catch (IOException e) {

  e.printStackTrace();

  }

  }

  }

  groovy解析实现:

  def emails = new XmlParser().parse(“emails.xml”)

  emails.email.each {

  println “${it.@id} ${it.subject.text()} ”

  }

  可以看到groovy解析代码之少,实现之简单。

分享到:
0
相关阅读
友情链接
© 2018 我考网 http://www.woexam.com 中国互联网举报中心 湘ICP备18023104号 京公网安备 11010802020116号
违法和不良信息举报:9447029@qq.com