JAXB与Stax
程序员文章站
2022-04-02 16:19:33
...
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Student {
private int id;
private String name;
private int age;
private Classroom classroom;
}
java转xml
JAXBContext ctx = JAXBContext.newInstance(Student.class);
Marshaller marshaller = ctx.createMarshaller();
Student stu = new Student(1,"张三",21,new Classroom(1,"10计算机应用技术",2010));
marshaller.marshal(stu, System.out);
xml转java
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><student><age>21</age><classroom><grade>2010</grade><id>1</id><name>10计算机应用技术</name></classroom><id>1</id><name>张三</name></student>";
JAXBContext ctx = JAXBContext.newInstance(Student.class);
Unmarshaller um = ctx.createUnmarshaller();
Student stu = (Student)um.unmarshal(new StringReader(xml));
Stax:待处理的的xml文件
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
XMLStreamReader reader = factory.createXMLStreamReader(is);
while(reader.hasNext()) {
int type = reader.next();
if(type==XMLStreamConstants.START_ELEMENT) {
String name = reader.getName().toString();
if(name.equals("book")) {
System.out.println(reader.getAttributeName(0)+":"+reader.getAttributeValue(0));
}
}
}
XMLInputFactory factory = XMLInputFactory.newInstance();
InputStream is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//基于迭代模型的操作方<br> XMLEventReader reader = factory.createXMLEventReader(is);
while(reader.hasNext()) {
//通过XMLEvent来获取是否是某种节点类型
XMLEvent event = reader.nextEvent();
if(event.isStartElement()) {
//通过event.asxxx转换节点
String name = event.asStartElement().getName().toString();
if(name.equals("title")) {
System.out.print(reader.getElementText()+":");
}
if(name.equals("price")) {
System.out.print(reader.getElementText()+"\n");
}
}
}
基于XPATH的处理
InputStream is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
//创建文档处理对象
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//通过DocumentBuilder创建doc的文档对象
Document doc = db.parse(is);
//创建XPath
XPath xpath = XPathFactory.newInstance().newXPath();
//第一个参数就是xpath,第二参数就是文档
NodeList list = (NodeList)xpath.evaluate("//book[@category='WEB']", doc,XPathConstants.NODESET);
for(int i=0;i<list.getLength();i++) {
//遍历输出相应的结果
Element e = (Element)list.item(i);
System.out.println(e.getElementsByTagName("title").item(0).getTextContent());
}