wzdoxu 发表于 2013-1-27 04:50:39

JAVA读取XML文件

请用JAVA编一段程序 读取一个XML文件
XML代码:

<?xml version="1.0" encoding="GB2312" ?>
<Root>
<Header left="100" Top="30">日报表</Header>
</Root>

并按照XML里描述的位置 把表头“日报表”三个字打印出来

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.NodeList;

public class Xml {
public static void main(String[] args) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("E:\\新建 文本文档 (3).xml"));
Element rootElement = document.getDocumentElement();

NodeList list = rootElement.getElementsByTagName("Header");
Element element = (Element) list.item(0);
System.out.println(element.getChildNodes().item(0).getNodeValue());

} catch (Exception e) {
System.out.println("exception:" + e.getMessage());
}
}
}

用 java 从 XML 文件里按照位置提取一些数据的方法有 3 种以上。最直观、方便的是利用 XPath 表达式:


import javax.xml.xpath.*;
import org.xml.sax.*;

class ExtractXMLDataByXpath {
    public static void main(String[] args) throws Exception {
      XPath xpathEngine = XPathFactory.newInstance().newXPath();
      String xpathExpression = "/Root/Header/text()";
      InputSource xmlSource = new InputSource("C:\\a.xml");    // 假设 XML 文件路径为 C:\a.xml
      System.out.println(xpathEngine.evaluate(xpathExpression, xmlSource));
    }
}
页: [1]
查看完整版本: JAVA读取XML文件