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