How to Parse or Read XML File in Java >> XML Tutorial Example
2013-11-16 13:39
573 查看
How to parse xml file in Java or how to read xml file in java is one of common need of a Java Developer working
with enterprise Java application which uses XML for data representation, messaging and data transfer. Java has good support tohandle
XML files and XML Documents and you canread XML File in Java,
create or write to XML file in Java by using variousXML parsers
available. Reading XML file is little bit different thanreading text or binary file in Java but it uses same concept of File class.
Universal
acceptability of XML and Java has helped them to grow together and they have lot of things common in between just likeJava is platform independence, XML provides data which is also platform independent. You can use XML to transfer data between a legacy
application written in C or C++ and Java.
What is important to work with XML in Java is correct understanding of XML Parser, Basic knowledge of XML document etc. In this Java XML Tutorial we will seehow to parse and XML File by using both DOM XML Parser. We will
also seedifference between DOM and SAX parser in XML
and other basics related to XML parsing in Java. I thought about this article after sharing myxpath notes in Java.
XML file. All XML parsing related classes and methods are inside JAXP. Though DOM related code comes from org.w3c.dompackage.
All XML parsers are injavax.xml.parsers package.we will see example of parsing xml files using JAXP API in next section.
how to read xml file using DOM XML Parser.DOM is quick and easy way to parse xml files in Java and if you are doing it for testing its way to go. Only thing to concern is that XML files which need to be parsed must not be too large. You can
also create xml file by using DOM parser and DocumentFactory
Class in Java.
XML file for parsing in Java
Here is xml file Stocks.xml which contains some stocks and there price, quantity we will use this in our xml parsing example in Java.
<?xmlversion="1.0"encoding="UTF-8"?>
<stocks>
<stock>
<symbol>Citibank</symbol>
<price>100</price>
<quantity>1000</quantity>
</stock>
<stock>
<symbol>Axis bank</symbol>
<price>90</price>
<quantity>2000</quantity>
</stock>
</stocks>
Code Example of Parsing XML File in Java using DOM Parser
Here is a code example of parsing above xml file in Java using DOM parser:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
publicclass DOMExampleJava {
publicstaticvoid main(String args[]) {
try {
File stocks = new File("Stocks.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(stocks);
doc.getDocumentElement().normalize();
System.out.println("root of xml file" + doc.getDocumentElement().getNodeName());
NodeList nodes = doc.getElementsByTagName("stock");
System.out.println("==========================");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("Stock Symbol: " +getValue("symbol",
element));
System.out.println("Stock Price:
" + getValue("price", element));
System.out.println("Stock Quantity: " +getValue("quantity",
element));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
privatestatic String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
}
Output:
root of xml file stocks
==========================
StockSymbol:Citibank
Stock Price: 100
Stock Quantity: 1000
Stock Symbol: Axis bank
Stock Price: 90
Stock Quantity: 2000
That’s all on xml parsing in java for now. We have seen how to read and write xml file in Java and now familiar with bothDOM and SAX Parser in java. We will see more on xml on coming days like
reading xml elements via xpath and using xml beans etc. let me know if you have any doubt on xml parsing example or in general with xml and Java.
Read more: http://javarevisited.blogspot.com/2011/12/parse-xml-file-in-java-example-tutorial.html#ixzz2ki8cP3Do
with enterprise Java application which uses XML for data representation, messaging and data transfer. Java has good support tohandle
XML files and XML Documents and you canread XML File in Java,
create or write to XML file in Java by using variousXML parsers
available. Reading XML file is little bit different thanreading text or binary file in Java but it uses same concept of File class.
Universal
acceptability of XML and Java has helped them to grow together and they have lot of things common in between just likeJava is platform independence, XML provides data which is also platform independent. You can use XML to transfer data between a legacy
application written in C or C++ and Java.
What is important to work with XML in Java is correct understanding of XML Parser, Basic knowledge of XML document etc. In this Java XML Tutorial we will seehow to parse and XML File by using both DOM XML Parser. We will
also seedifference between DOM and SAX parser in XML
and other basics related to XML parsing in Java. I thought about this article after sharing myxpath notes in Java.
How to read XML File in Java
JAXP - Java API for XML Parsing
Java provides extensive support for reading XML file, writing XML file and accessing any element fromXML file. All XML parsing related classes and methods are inside JAXP. Though DOM related code comes from org.w3c.dompackage.
All XML parsers are injavax.xml.parsers package.we will see example of parsing xml files using JAXP API in next section.
Parse XML File in Java using DOM Parser
In this section we will see how to parse xml filesorhow to read xml file using DOM XML Parser.DOM is quick and easy way to parse xml files in Java and if you are doing it for testing its way to go. Only thing to concern is that XML files which need to be parsed must not be too large. You can
also create xml file by using DOM parser and DocumentFactory
Class in Java.
XML file for parsing in Java
Here is xml file Stocks.xml which contains some stocks and there price, quantity we will use this in our xml parsing example in Java.
<?xmlversion="1.0"encoding="UTF-8"?>
<stocks>
<stock>
<symbol>Citibank</symbol>
<price>100</price>
<quantity>1000</quantity>
</stock>
<stock>
<symbol>Axis bank</symbol>
<price>90</price>
<quantity>2000</quantity>
</stock>
</stocks>
Code Example of Parsing XML File in Java using DOM Parser
Here is a code example of parsing above xml file in Java using DOM parser:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
publicclass DOMExampleJava {
publicstaticvoid main(String args[]) {
try {
File stocks = new File("Stocks.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(stocks);
doc.getDocumentElement().normalize();
System.out.println("root of xml file" + doc.getDocumentElement().getNodeName());
NodeList nodes = doc.getElementsByTagName("stock");
System.out.println("==========================");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println("Stock Symbol: " +getValue("symbol",
element));
System.out.println("Stock Price:
" + getValue("price", element));
System.out.println("Stock Quantity: " +getValue("quantity",
element));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
privatestatic String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
}
Output:
root of xml file stocks
==========================
StockSymbol:Citibank
Stock Price: 100
Stock Quantity: 1000
Stock Symbol: Axis bank
Stock Price: 90
Stock Quantity: 2000
That’s all on xml parsing in java for now. We have seen how to read and write xml file in Java and now familiar with bothDOM and SAX Parser in java. We will see more on xml on coming days like
reading xml elements via xpath and using xml beans etc. let me know if you have any doubt on xml parsing example or in general with xml and Java.
Read more: http://javarevisited.blogspot.com/2011/12/parse-xml-file-in-java-example-tutorial.html#ixzz2ki8cP3Do
相关文章推荐
- How To Read XML File In Java – (SAX Parser)
- Step By Step guide to Read XML file in Java Using SAX Parser Example
- How to read file in Java – BufferedInputStream Example
- How To Read XML File In Java – (DOM Parser)
- How to read and parse CSV file in Java
- How to Read, Write XLSX File in Java - Apach POI Example---reference
- How to override compareTo method in Java - Example Tutorial
- How to use ConcurrentHashMap in Java - Example Tutorial and Working
- How to read Json file or text file in Spark
- Units Problem: How to read text size as custom attr from xml and set it to TextView in java code
- Units Problem: How to read text size as custom attr from xml and set it to TextView in java code
- How to Create and Evaluate XPath Expression in Java - Tutorial and Example
- PDFBox – How to read PDF file in Java
- How to read Mac .DMG file in Linux or PC
- A simple way to read an XML file in Java
- How to Read XMLDocument into a SQL Sever XML field / saving XML to database or filesystem...best method?
- How To Create XML File In Java – (DOM Parser)
- How to decompile class file in Java and Eclipse - Javap command example(转)
- How to read Mac .DMG file in Linux or PC(II)
- Units Problem: How to read text size as custom attr from xml and set it to TextView in java code