Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, i have a question about parsing file in Java.
How would i parse a specific line in file such as XML or txt file and is static so i can use it anywhere in the applet? Below is example of text i want to parse.

For XML file


<configuration>
	<main>
		<theme>com.sun.java.swing.plaf.windows.WindowsLookAndFeel</theme>
	</main>
</configuration>


For text file

[Configuration]
Theme=com.sun.java.swing.plaf.windows.WindowsLookAndFeel


Thanks alot!
Posted

For parsing the XML use XPath[^] and for the text file based approach use Java Property Riles[^].

Hope that helps a bit.

Cheers!

-MRB
 
Share this answer
 
v2
Thanks im going to try it and tell you if it works or not!

Edited: See i tried using DOM Parser and it works but the thing would be that its not static meaning i cannot use it globally!

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
 
public class ReadXMLFile {
 
 public static void main(String argv[]) {
 
 try {
 
    File fXmlFile = new File("file.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();
 
    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("Configuration");
    System.out.println("-----------------------");
 
    for (int temp = 0; temp < nList.getLength(); temp++) {
 
       Node nNode = nList.item(temp);	    
       if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
          Element eElement = (Element) nNode;
 
          System.out.println("Theme : "  + getTagValue("theme",eElement));
 
        }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
 }
 
 private static String getTagValue(String sTag, Element eElement){
    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0); 
 
    return nValue.getNodeValue();    
 }
 
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900