Java中读取XML⽂件,⽣成XML格式的字符串并解析这个字符
由于最近要⽤的是XML格式的字符串,⽽不⽤写到⽂件中,所以对原始代码进⾏了修改如下:
要读的xml⽂件
<?xml version="1.0" encoding="GB2312"?>
<;学⽣花名册>
<;学⽣性别 = "男">
<;姓名>李华</姓名>
<;年龄>14</年龄>
</学⽣>
<;学⽣性别 = "男">
<;姓名>张三</姓名>
<;年龄>16</年龄>
</学⽣>
</学⽣花名册>
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import java.util.Vector;
l.parsers.DocumentBuilder;
l.parsers.DocumentBuilderFactory;
l.transform.OutputKeys;
l.transform.Result;
l.transform.Source;
l.transform.Transformer;
l.transform.TransformerConfigurationException;
l.transform.TransformerException;
l.transform.TransformerFactory;
l.transform.dom.DOMSource;
l.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
public class DomTest {
Vector students_Vector;
private Vector readXMLFile(String file) throws Exception {
DocumentBuilderFactory dbf = wInstance();
DocumentBuilder builder = wDocumentBuilder();
Document doc = builder.parse(file); // 获取到xml⽂件
// 下⾯开始读取
Element root = DocumentElement(); // 获取根元素
NodeList students = ElementsByTagName("学⽣");
students_Vector = new Vector();
for (int i = 0; i < Length(); i++) {
// ⼀次取得每⼀个学⽣元素
Element ss = (Element) students.item(i);
// 创建⼀个学⽣的实例
java xml是什么student stu = new student();
stu.Attribute("性别"));
NodeList names = ss.getElementsByTagName("姓名");
Element e = (Element) names.item(0);
Node t = e.getFirstChild();
stu.NodeValue());
NodeList ages = ss.getElementsByTagName("年龄");
e = (Element) ages.item(0);
t = e.getFirstChild();
stu.setAge(Integer.NodeValue()));
students_Vector.add(stu);
}
return students_Vector;
}
}
/
**
* 功能:直接提取XML格式字符串中的信息
*/
private Vector readXMLString(String xmlStr) throws Exception {
DocumentBuilderFactory dbf = wInstance();        DocumentBuilder builder = wDocumentBuilder();
InputStream inputStream = new Bytes());        Document doc = builder.parse(inputStream); //
// 下⾯开始读取
Element root = DocumentElement(); // 获取根元素
NodeList students = ElementsByTagName("学⽣");
students_Vector = new Vector();
for (int i = 0; i < Length(); i++) {
// ⼀次取得每⼀个学⽣元素
Element ss = (Element) students.item(i);
// 创建⼀个学⽣的实例
student stu = new student();
stu.Attribute("性别"));
NodeList names = ss.getElementsByTagName("姓名");
Element e = (Element) names.item(0);
Node t = e.getFirstChild();
stu.NodeValue());
NodeList ages = ss.getElementsByTagName("年龄");
e = (Element) ages.item(0);
t = e.getFirstChild();
stu.setAge(Integer.NodeValue()));
students_Vector.add(stu);
}
return students_Vector;
}
// 将Document内容写⼊XML字符串并返回
private String callWriteXmlString(Document doc, String encoding) {
try {
Source source = new DOMSource(doc);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
OutputStreamWriter write = new OutputStreamWriter(outStream);
Result result = new StreamResult(write);
Transformer xformer = wInstance()
.newTransformer();
xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
String();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
return null;
} catch (TransformerException e) {
e.printStackTrace();
return null;
}
}
/**
* 功能:⽣成XML格式的字符串
*/
public String writeXMLString() {
DocumentBuilderFactory dbf = wInstance();        DocumentBuilder builder = null;
try {
builder = wDocumentBuilder();
} catch (Exception e) {
}
Document doc = wDocument();
Element root = ateElement("学⽣花名册");
doc.appendChild(root); // 将根元素添加到⽂档上
// 获取学⽣信息
for (int i = 0; i < students_Vector.size(); i++) {
student s = (student) (i);
student s = (student) (i);
// 创建⼀个学⽣
Element stu = ateElement("学⽣");
stu.setAttribute("性别", s.getSex());
root.appendChild(stu);// 添加属性
// 创建⽂本姓名节点
Element name = ateElement("姓名");
stu.appendChild(name);
Text tname = Name());
name.appendChild(tname);
// 创建⽂本年龄节点
Element age = ateElement("年龄");
stu.appendChild(age); // 将age添加到学⽣节点上
Text tage = ateTextNode(String.Age()));            age.appendChild(tage); // 将⽂本节点放在age节点上
}
try {
String result = callWriteXmlString(doc, "gb2312");
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 主函数
*/
public static void main(String args[]) {
String str = "xml\\l";
DomTest t = new DomTest();
System.out.println("解析原始XML⽂件:");
try {
Vector v = t.readXMLFile(str);
Iterator it = v.iterator();
while (it.hasNext()) {
student s = (student) it.next();
System.out.Name() + "\t" + s.getAge() + "\t"
+ s.getSex());
}
} catch (Exception e) {
e.printStackTrace();
}
String xmlStr = t.writeXMLString();
System.out.println("\n⽣成的XML字符串:\n" + xmlStr);
try {
Vector v = t.readXMLString(xmlStr);
Iterator it = v.iterator();
System.out.println("\n解析⽣成的XML字符串:");
while (it.hasNext()) {
student s = (student) it.next();
System.out.Name() + "\t" + s.getAge() + "\t"
+ s.getSex());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class student {
private String sex;
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setSex(String s) {
sex = s;
}
}
public String getSex() {
return sex;
}
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
}
输出:
解析原始XML⽂件:
李华    14    男
张三    16    男
⽣成的XML字符串:
<?xml version="1.0" encoding="GB2312" standalone="no"?><;学⽣花名册><;学⽣性别="男"><;姓名>李华</姓名><;年龄>14</年龄></学⽣><;学⽣性别="男"><;姓名>张三</姓名><;年龄>16</年龄></学⽣></学⽣花名册>
解析⽣成的XML字符串:
李华    14    男
张三    16    男

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。