Arquivo

Posts Tagged ‘read’

Reading XML with Java – Quick and simple example

I always need some code to read XML with Java. This is a place holder to me, but, maybe can be useful to other people.

Here is my XML example:

<operator logic="and">
<operator logic="or">
<term field="query" input-type="user" processing="strict" str="は" />
<term field="query" input-type="user" phrase="phrase" processing="strict" str="銀行業務" weight="1" />
<term field="query" input-type="user" processing="strict" str="持つ" />
<term field="query" input-type="user" phrase="phrase" processing="strict" str="java開発者" weight="1.69" />
<term field="query" input-type="user" processing="strict" str="探して" />
</operator>
</operator>

Here is my Java code:

import org.w3c.dom.*;
import org.xml.sax.InputSource;

import javax.xml.parsers.*;
import java.io.*;

public class ParseXML {

	public static void main(String[] args) {
		String xml = "<operator logic=\"or\"><term field=\"query\" input-type=\"user\" processing=\"strict\" str=\"は\" /><term field=\"query\" input-type=\"user\" phrase=\"phrase\" processing=\"strict\" str=\"銀行業務\" weight=\"1\" /><term field=\"query\" input-type=\"user\" processing=\"strict\" str=\"持つ\" /><term field=\"query\" input-type=\"user\" phrase=\"phrase\" processing=\"strict\" str=\"java開発者\" weight=\"1.69\" /><term field=\"query\" input-type=\"user\" processing=\"strict\" str=\"探して\" /></operator>";
		try {	
			Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
			doc.getDocumentElement().normalize();
			
			System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
			NodeList nList = doc.getElementsByTagName("term");
			System.out.println("----------------------------");
			for (int temp = 0; temp < nList.getLength(); temp++) {
				Node nNode = nList.item(temp);
				System.out.println("\nCurrent Element :" + nNode.getNodeName());
				if (nNode.getNodeType() == Node.ELEMENT_NODE) {
					Element eElement = (Element) nNode;
					System.out.println("processing : " + eElement.getAttribute("processing"));
					System.out.println("str : " + eElement.getAttribute("str"));
	            }
	         }
	      } catch (Exception e) {
	         e.printStackTrace();
	      }
	}
}
Categorias:JAVA Tags:, , , , , , ,