Java解析XML或文本文件 [英] Java Parse XML or text file
本文介绍了Java解析XML或文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个有关在Java中解析文件的问题.
我将如何解析文件中的特定行(例如XML或txt文件),并且该行是静态的,因此可以在applet中的任何位置使用它?以下是我要解析的文本示例.
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!
推荐答案
要解析XML,请使用 ^ ],对于基于文本文件的方法,请使用^ ].
希望能有所帮助.
干杯!
-MRB
For parsing the XML use XPath[^] and for the text file based approach use Java Property Riles[^].
Hope that helps a bit.
Cheers!
-MRB
感谢即时消息,请尝试并告诉它是否有效!
看到我尝试使用DOM分析器,它可以工作,但事实是它不是静态的,所以我不能在全球范围内使用它!
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();
}
}
这篇关于Java解析XML或文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文