XML读取数据
采用文件流怎样读取解析XML文档,最好有案例?
[解决办法]
dom4j 引用个开源项目即可
[解决办法]
我这里有个dom4j的。jar包 dom4j1.6.1.jar。
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
* 用dom4j生成条形码的XML格式:
* <barcodeInfo>
<barcodeString>1231231</barcodeString>
<writeTimeString>2012-3-13 13:23:32</writeTimeString>
</barcodeInfo>
* @author wfg
*/
public class DOM4jXML {
/**
*
* @param 文件名(XXX.xml)
* @param Str 字符串
* @param timeStr 时间字符串
*/
public static void createBarcodeXml(String fileName,String barcodeStr,String timeStr)
{
Document document = DocumentHelper.createDocument(); //创建文档
Element barcodeInfo=document.addElement("barcodeInfo");
Element barcodeString=barcodeInfo.addElement("barcodeString");
Element writeTime=barcodeInfo.addElement("writeTimeString");
barcodeString.setText(barcodeStr);
writeTime.setText(timeStr);
try {
Writer fileWriter=new FileWriter(fileName);
XMLWriter xmlWriter=new XMLWriter(fileWriter);
xmlWriter.write(document); //写入文件中
xmlWriter.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
/**
* 读取xml文件
* @param fileName
*/
void parserXml(String fileName)
{
File inputXml=new File(fileName);
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(inputXml); //把文件读入到文档
Element barcodeInfo=document.getRootElement(); //获取文档根节点
this.doublexml(barcodeInfo);
} catch (DocumentException e) {
System.out.println(e.getMessage());
}
}
private void doublexml(Element ele)
{
StringBuilder sb = new StringBuilder();
for(Iterator i = ele.elementIterator();i.hasNext();)
{
Element node = (Element)i.next();
System.out.println("节点名:"+node.getName());
String nodeName = node.getName();
if(node.attributes()!=null && node.attributes().size()>0)
{
for(Iterator j = node.attributeIterator();j.hasNext();)
{
Attribute item = (Attribute)j.next();
System.out.print("属性名:"+item.getName()+"\t属性值:"+item.getValue()+"\n");
}
}
if(node.getText().length()>0)
{
System.out.println("节点值:"+node.getText());
String nodeText = node.getText();
}
if(node.elementIterator().hasNext())
{
this.doublexml(node);
}
}
}
}
//测试用例:
DOM4jXML demo = new DOM4jXML();
//写xml
demo.createBarcodeXml("f:/sa2.xml","1231231","2012-3-13 13:23:32");
//读xml
demo.parserXml("h:/test.xml");