java

位置:IT落伍者 >> java >> 浏览文章

比较groovy/java解析xml文件


发布日期:2023年08月23日
 
比较groovy/java解析xml文件

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解析代码之少实现之简单

               

上一篇:Java ME中的Math.pow()方法使用详解

下一篇:企业版JavaBean讨论