您的位置:首页 > 其它

如何获得XML文件中的内容?

2006-08-08 21:22 295 查看
比如现在有xml文件:

Test.xml:

<?xml version="1.0"?>
<products>
<product id="1001">
<name>test1</name>
<price>25</price>
</product>
<product id="1002">
<name>test2</name>
<price>45</price>
</product>
<product id="1003">
<name>test3</name>
<price>56</price>
</product>
</products>

新建JAVA类.来读取XML文件.
TestClass.java

package services;

import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;

public class TestClass {
public static void main(String[] args) {
//读取XML文件例子
File docFile=new File("Product.xml");
Document doc=null;
DocumentBuilderFactory dbf= DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
doc=db.parse(docFile);
} catch (ParserConfigurationException ex) {
System.out.println(ex.toString());
} catch (IOException ex) {
System.out.println(ex.toString());
} catch (SAXException ex) {
System.out.println(ex.toString());
}

NodeList products=doc.getElementsByTagName("product");
Element productElement;
for(int i=0;i<products.getLength();i++){
productElement=(Element)products.item(i);
String id=productElement.getAttribute("id");
System.out.println("ID:"+id);

String name=doc.getElementsByTagName("name").item(i).getFirstChild().getNodeValue();
System.out.println("Name:"+name);

String price=doc.getElementsByTagName("price").item(i).getFirstChild().getNodeValue();
System.out.println ("price:"+price);
System.out.println("---------------");
}
}
}

然后点编译.
即可在控制台上看到输出结果:
ID:1001

Name:test1

price:25

---------------

ID:1002

Name:test2

price:45

---------------

ID:1003

Name:test3

price:56

---------------

本例子中读取文件的关键是导入的几个类的功劳.

下面几个是在spring中获得配置文件xml文件:

package com.openv.spring;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class HelloWorldClient {
protected static final Log log = LogFactory.getLog(HelloWorldClient.class);

public HelloWorldClient() {
Resource resource = new ClassPathResource("appcontext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
HelloWorld hw = (HelloWorld) factory.getBean("fileHelloWorld");
log.info(hw.getContent());
}

public static void main(String[] args) {
new HelloWorldClient();
}
}

另外一种方式:

InputStream ins=new FileInputSrteam("src/appcontent.xml");

BeanFactory factory=new XmlBeanFactory(ins);

HelloWorld hw = (HelloWorld) factory.getBean("fileHelloWorld");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: