熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

比較groovy/java解析xml文件

2022-06-13   來源: Java核心技術 

  xml內容

  <emails>

  <email id=′>

  <subject>hello world</subject>

  <sender></sender>

  <receivedDate> ::</receivedDate>

  </email>

  <email id=′>

  <subject>hello world demo </subject>

  <sender></sender>

  <receivedDate> ::</receivedDate>

  </email>

  <email id=′>

  <subject>hello world demo </subject>

  <sender></sender>

  <receivedDate> ::</receivedDate>

  </email>

  </emails>

  java解析實現

  import orgwcdomDocument;

  import orgwcdomNode;

  import orgwcdomNodeList;

  import orgxmlsaxSAXException;

  import javaxxmlparsersDocumentBuilder;

  import javaxxmlparsersDocumentBuilderFactory;

  import javaxxmlparsersParserConfigurationException;

  import javaioIOException;

  import javaioInputStream;

  public class EmailsDemo {

  public static void main(String[] args)

  {

  DocumentBuilderFactory factory = DocumentBuilderFactorynewInstance();

  try {

  DocumentBuilder builder = factorynewDocumentBuilder();

  InputStream is = EmailsDemoclassgetResourceAsStream(/emailsxml);

  Document document = builderparse(is);

  NodeList nodes = documentgetElementsByTagName(email);

  for (int i = ; i < nodesgetLength(); i++)

  {

  Node node = em(i);

  Node id = nodegetAttributes()getNamedItem(id);

  Systemoutprintln(id = + idgetTextContent());

  }

  } catch (ParserConfigurationException e) {

  eprintStackTrace();

  } catch (SAXException e) {

  eprintStackTrace();

  } catch (IOException e) {

  eprintStackTrace();

  }

  }

  }

  groovy解析實現

  def emails = new XmlParser()parse(emailsxml)

  emailsemaileach {

  println ${it@id} ${itsubjecttext()}

  }

  可以看到groovy解析代碼之少實現之簡單


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26896.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.