Java操作xml(使用javax.xml)

本文介绍了一个使用Java进行XML序列化和反序列化的简单示例。通过JAXB (Java Architecture for XML Binding) 实现了对象到XML文件的转换及从XML文件读取对象的过程。示例中定义了两个类`A`和`B`,并展示了如何将这些类实例化后的对象写入XML文件,以及如何从XML文件中读取这些对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class test extends DefaultHandler {

	public static void main(String[] args) throws ParserConfigurationException,
			SAXException, IOException, JAXBException {

		OutputStream os = new FileOutputStream("c:\\1.xml");
		JAXBContext jc0 = JAXBContext.newInstance(A.class);
		Marshaller m = jc0.createMarshaller();
		A a = new A();
		a.setId("id for a");
		B b = new B();
		b.setNo(60);
		a.setB(b);
		m.marshal(a, os);

		InputStream is = new FileInputStream("c:\\1.xml");
		JAXBContext jc = JAXBContext.newInstance(A.class);
		Unmarshaller u = jc.createUnmarshaller();
		A o = (A) u.unmarshal(is);
		System.out.println(o.getB().getNo());

	}
}

@XmlRootElement(name = "A")
class A {
	String id;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public B getB() {
		return b;
	}

	public void setB(B b) {
		this.b = b;
	}

	B b;

}

class B {

	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	int no;
}

 

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><A><b><no>60</no></b><id>id for a</id></A>
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值