007 import java.io.*;
008 import org.w3c.dom.*;
009 import org.xml.sax.*;
010 import javax.xml.parsers.*;
011 import javax.xml.transform.*;
012 import javax.xml.transform.dom.*;
013 import javax.xml.transform.stream.*;
014
015 /** This class represents short example how to parse XML file,
016 * get XML nodes values and its values.
017 * It implements method to save XML document to XML file too
018 * @author Martin Glogar
019 */
020 public class ParseXMLFile {
021
022 private final static String xmlFileName = "c:/example.xml";
023 private final static String targetFileName = "c:/example2.xml";
024
025 /** Creates a new instance of ParseXMLFile */
026 public ParseXMLFile() {
027 // parse XML file -> XML document will be build
028 Document doc = parseFile(xmlFileName);
029 // get root node of xml tree structure
030 Node root = doc.getDocumentElement();
031 // write node and its child nodes into System.out
032 System.out.println("Statemend of XML document...");
033 writeDocumentToOutput(root,0);
034 System.out.println("... end of statement");
035 // write Document into XML file
036 saveXMLDocument(targetFileName, doc);
037 }
038
039 /** Returns element value
040 * @param elem element (it is XML tag)
041 * @return Element value otherwise empty String
042 */
043 public final static String getElementValue( Node elem ) {
044 Node kid;
045 if( elem != null){
046 if (elem.hasChildNodes()){
047 for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
048 if( kid.getNodeType() == Node.TEXT_NODE ){
049 return kid.getNodeValue();
050 }
051 }
052 }
053 }
054 return "";
055 }
056
057 private String getIndentSpaces(int indent) {
058 StringBuffer buffer = new StringBuffer();
059 for (int i = 0; i < indent; i++) {
060 buffer.append(" ");
061 }
062 return buffer.toString();
063 }
064
065 /** Writes node and all child nodes into System.out
066 * @param node XML node from from XML tree wrom which will output statement start
067 * @param indent number of spaces used to indent output
068 */
069 public void writeDocumentToOutput(Node node,int indent) {
070 // get element name
071 String nodeName = node.getNodeName();
072 // get element value
073 String nodeValue = getElementValue(node);
074 // get attributes of element
075 NamedNodeMap attributes = node.getAttributes();
076 System.out.println(getIndentSpaces(indent) + "NodeName: " + nodeName + ", NodeValue: " + nodeValue);
077 for (int i = 0; i < attributes.getLength(); i++) {
078 Node attribute = attributes.item(i);
079 System.out.println(getIndentSpaces(indent + 2) + "AttributeName: " + attribute.getNodeName() + ", attributeValue: " + attribute.getNodeValue());
080 }
081 // write all child nodes recursively
082 NodeList children = node.getChildNodes();
083 for (int i = 0; i < children.getLength(); i++) {
084 Node child = children.item(i);
085 if (child.getNodeType() == Node.ELEMENT_NODE) {
086 writeDocumentToOutput(child,indent + 2);
087 }
088 }
089 }
090
091 /** Saves XML Document into XML file.
092 * @param fileName XML file name
093 * @param doc XML document to save
094 * @return
true if method success
false otherwise
095 */
096 public boolean saveXMLDocument(String fileName, Document doc) {
097 System.out.println("Saving XML file... " + fileName);
098 // open output stream where XML Document will be saved
099 File xmlOutputFile = new File(fileName);
100 FileOutputStream fos;
101 Transformer transformer;
102 try {
103 fos = new FileOutputStream(xmlOutputFile);
104 }
105 catch (FileNotFoundException e) {
106 System.out.println("Error occured: " + e.getMessage());
107 return false;
108 }
109 // Use a Transformer for output
110 TransformerFactory transformerFactory = TransformerFactory.newInstance();
111 try {
112 transformer = transformerFactory.newTransformer();
113 }
114 catch (TransformerConfigurationException e) {
115 System.out.println("Transformer configuration error: " + e.getMessage());
116 return false;
117 }
118 DOMSource source = new DOMSource(doc);
119 StreamResult result = new StreamResult(fos);
120 // transform source into result will do save
121 try {
122 transformer.transform(source, result);
123 }
124 catch (TransformerException e) {
125 System.out.println("Error transform: " + e.getMessage());
126 }
127 System.out.println("XML file saved.");
128 return true;
129 }
130
131 /** Parses XML file and returns XML document.
132 * @param fileName XML file to parse
133 * @return XML document or
null if error occured
134 */
135 public Document parseFile(String fileName) {
136 System.out.println("Parsing XML file... " + fileName);
137 DocumentBuilder docBuilder;
138 Document doc = null;
139 DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
140 docBuilderFactory.setIgnoringElementContentWhitespace(true);
141 try {
142 docBuilder = docBuilderFactory.newDocumentBuilder();
143 }
144 catch (ParserConfigurationException e) {
145 System.out.println("Wrong parser configuration: " + e.getMessage());
146 return null;
147 }
148 File sourceFile = new File(fileName);
149 try {
150 doc = docBuilder.parse(sourceFile);
151 }
152 catch (SAXException e) {
153 System.out.println("Wrong XML file structure: " + e.getMessage());
154 return null;
155 }
156 catch (IOException e) {
157 System.out.println("Could not read source file: " + e.getMessage());
158 }
159 System.out.println("XML file parsed");
160 return doc;
161 }
162
163 /** Starts XML parsing example
164 * @param args the command line arguments
165 */
166 public static void main(String[] args) {
167 new ParseXMLFile();
168 }
169
170 }