日期:2014-05-20  浏览次数:20893 次

关于XML
package un.its.manager;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

public class Text {
public static void main(String args[]){
try{  
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document document=builder.newDocument();
document.setXmlVersion("1.0");
int e1,e2;
int laneNum;
laneNum=(int)(Math.random()*1000)+1;
String Strat1,Strat2;
double d = Math.random();
Random r=new Random(1);
String there=null;
if (d < 0.5) {
there="1";
}else {
there="0";
}
e2=r.nextInt(2000)+1;
e1=r.nextInt(99)+1;
Strat1=String.valueOf(e1) ;
Strat2=String.valueOf(e2) ;

System.out.println("是否为双向道路isDouble:"+there);
System.out.println("路段roadID:"+ Strat1);
System.out.println("车道数量:"+laneNum);
System.out.println( "路段长度roadLength:"+Strat2 +"该路段上所允许的最大行车速度maxspeed:"+Strat1+"路口ID:"+Strat1);
TransformerFactory transFactory=TransformerFactory.newInstance();
Transformer transformer=transFactory.newTransformer();
DOMSource domSource=new DOMSource(document);
File file=new File("E:/score3.xml");
FileOutputStream out=new FileOutputStream(file);
StreamResult xmlResult=new StreamResult(out);
transformer.transform(domSource,xmlResult);
}
catch(Exception e){
System.out.println("Score3.java:"+e);
}
}
}
结果是无法显示 XML 页。 
使用 样式表无法查看 XML 输入。请更正错误然后单击 刷新按钮,或以后重试。 


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

系统不支持指定的编码方式。处理资源 'file:///E:/score3.xml' 时出错。第 1 行,位置: 55 

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

 
请求高人指点

------解决方案--------------------
不是编码的问题,是你的数据都没有写进去,只创建了个document.setXmlVersion("1.0");
 xml的头,score3.xml里都是空的
------解决方案--------------------
给你个例子:
public class DomWriter {
 public static void main(String[] args)throws Exception {
//document---documentBuilder-----documentBuilderFactory
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.newDocument();
  
//创建元素
Element root=doc.createElement("students");
Element student=doc.createElement("student");
Element name=doc.createElement("name");
Element sex=doc.createElement("sex");
Element age=doc.createElement("age");
  
//添加层次关系---子元素
doc.appendChild(root);
root.appendChild(student);
student.appendChild(name);
student.appendChild(sex);
student.appendChild(age);
  
//给元素添加属性 文本内容
student.setAttribute("id","001");
  
name.setTextContent("张三");
sex.setTextContent("男");
age.setTextContent("10");
  
//将document写入文件
File file=new File("src\\xml\\dom.xml");
file.createNewFile();