以下是我学习webService视频的学习笔记:
Java类和XML之间的转换.编排:class转换为XML
反编排:xml转换为class
Java读取xml三种方式Stream
Event
Xpath
Java中使用XMLStreamWriter写入XML
Java中使用TransFormer修改XML
1.Java类和XML之间的转换.
ClassInfo.java代码:
public classClassInfo {private intid;privateString className;public ClassInfo(intid, String className) {super();this.id =id;this.className =className;
}publicClassInfo() {super();
}//..省略getter/setter方法...
}
StudentInfo.java代码:
@XmlRootElementpublic classStudentInfo {private intid;privateString stuName;privateClassInfo classInfo;publicStudentInfo() {super();
}public StudentInfo(intid, String stuName) {super();this.id =id;this.stuName =stuName;
}//..省略getter/setter方法
}
编排测试方法如下:
//编排
@Testpublic voidtest01() {try{//使用JAXB方式编排,获取JaxbContext对象 参数为需要编排的类
JAXBContext ctx = JAXBContext.newInstance(StudentInfo.class);//通过JaxbContext对象创建编排Marshaller对象
Marshaller marshaller =ctx.createMarshaller();
StudentInfo student= newStudentInfo();
student.setId(1);
student.setStuName("张璐");
student.setClassInfo(new ClassInfo(1, "java_1"));//调用编排 参数1:编排对象, 参数2:输出流
marshaller.marshal(student, System.out);
}catch(JAXBException e) {
e.printStackTrace();
}
}
PS:获取jaxbContext对象被作为参数的类,需要加上@XmlRootElement注解.如上的StudentInfo类
反编排测试代码如下:
//反编排
@Testpublic void test02() throwsException{//获取JaxbContext对象
JAXBContext ctx = JAXBContext.newInstance(StudentInfo.class);//创建反编排对象
Unmarshaller um =ctx.createUnmarshaller();//创建File,指定xml文件,System.getProperty("user.dir")获取项目路径
File file = new File(System.getProperty("user.dir")+ "/src/com/zhanglu/xml/studentInfo.xml");
StudentInfo stu= (StudentInfo) um.unmarshal(file);//进行反编排获取对象
System.out.println(stu.getStuName());
}
2.Java中读取XML
在项目的com.zhanglu.xml包中有如下booksxml文件. (来自W3CSHOOL)
Everyday Italian
Giada De Laurentiis
2005
30.00
Harry Potter
J K. Rowling
2005
29.99
XQuery Kick Start
James McGovern
Per Bothner
Kurt Cagle
James Linn
Vaidyanathan Nagarajan
2003
49.99
Learning XML
Erik T. Ray
2003
39.95
Stream以光标方式读取:
//使用Stream 光标方式
@Testpublic void textReader01() throwsException {
XMLInputFactory factory= XMLInputFactory.newInstance();//获取工厂
InputStream is = TestStax.class.getClassLoader().getResourceAsStream("com/zhanglu/xml/books.xml");//获取流
XMLStreamReader reader = factory.createXMLStreamReader(is);//创建stream读取对象
while (reader.hasNext()) {//如果有下文 循环读取
int tag = reader.next();//返回获取的下一个常量值
if (XMLStreamConstants.START_ELEMENT == tag) {//对常量进行判断,如果是开始节点
if (reader.getAttributeCount() > 0) {//如果节点的属性数理大于0
System.out.println(reader.getName());//获取节点名称
System.out.println(reader.getAttributeName(0) + "," + reader.getAttributeValue(0));//输出节点
}
}
}
}
Event迭代方式读取(普通迭代):
//迭代方式 EVENT
@Testpublic void textReader03() throwsException {
XMLInputFactory factory= XMLInputFactory.newInstance();//获取工厂
InputStream is = TestStax.class.getClassLoader().getResourceAsStream("com/zhanglu/xml/books.xml");//获取流//创建exent读取对象
XMLEventReader reader =factory.createXMLEventReader(is);while (reader.hasNext()) {//遍历
XMLEvent event = reader.nextEvent();//获取下一个Event
if (event.isStartElement()) {//如果是开始节点
System.out.println(event.asStartElement().toString());//输出//System.out.println(event.asStartElement().getName().toString());
}
}
}
Event迭代方式读取(使用过滤器来减少迭代次数):
//迭代方式 EVENT 使用过滤器 减少迭代次数
@Testpublic void textReader04() throwsException {XMLInputFactory factory= XMLInputFactory.newInstance();//获取工厂
InputStream is = TestStax.class.getClassLoader().getResourceAsStream("com/zhanglu/xml/books.xml");//获取流
XMLEventReader reader =factory.createFilteredReader(
factory.createXMLEventReader(is),new EventFilter() {//获取读取对象,重写EventFilter类的accept方法
@Overridepublic booleanaccept(XMLEvent event) {if (event.isStartElement()) {//如果是开始标签,返回true
return true;//这样就只会迭代开始标签
}return false;
}
});while(reader.hasNext()) {
XMLEvent event=reader.nextEvent();if (event.isStartElement()) {//判断是否为开始标签
System.out.println(event.asStartElement().toString());
}
}
}
XPath方式读取XML:
//使用Xpath 操作
@Testpublic void test01() throwsException{//创建输入流
InputStream is=TestXpathReader.class.getClassLoader().getResourceAsStream("com/zhanglu/xml/books.xml");//创建Xpath对象 通过Xpath工厂
XPath xpath=XPathFactory.newInstance().newXPath();//创建文档对象 通过文档构造工厂
DocumentBuilder db=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=db.parse(is);//获取节点集合 第一个参数 表达式 第二个文档 第三个Xpath
NodeList nodeList=(NodeList)xpath.evaluate("//book[@category='WEB']", doc,XPathConstants.NODESET);//遍历
for(int i=0;i
Element element=(Element)nodeList.item(i);
System.out.println(element.getElementsByTagName("author").item(0).getTextContent());
}
}
3.使用Java中的XMLStreamWriter写入一个XML
//使用 XMLStreamWriter 来写xml文件
@Testpublic void test01() throwsException{
FileOutputStream out=new FileOutputStream(new File(System.getProperty("user.dir")+"/src/com/zhanglu/xml/student.xml"));
XMLStreamWriter w=XMLOutputFactory.newInstance().createXMLStreamWriter(out);
w.writeStartDocument("UTF-8", "1.0");
w.writeEndDocument();
w.writeStartElement("student");
w.writeAttribute("stuId", "1");
w.writeStartElement("stuName");
w.writeCharacters("张三");
w.writeEndElement();
w.writeStartElement("stuSex");
w.writeCharacters("男");
w.writeEndElement();
w.writeStartElement("stuAddress");
w.writeCharacters("湖北襄阳");
w.writeEndElement();
w.writeEndElement();
w.flush();
out.close();
}
4.使用TransFormer来更新XML文件
//使用TransFormer更新xml文件
@Testpublic void test() throwsException {//创建输入流
InputStream is = TestTransFormerUpdate.class.getClassLoader().getResourceAsStream("com/zhanglu/xml/student.xml");//创建DocBuilder对象
DocumentBuilder db =DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc= db.parse(is);//获取document对象
XPath xpath = XPathFactory.newInstance().newXPath();//创建Xpath对象//创建transFormer对象
Transformer tran =TransformerFactory.newInstance().newTransformer();
tran.setOutputProperty(OutputKeys.ENCODING,"utf-8");//设置编码
tran.setOutputProperty(OutputKeys.INDENT, "yes");//支付插入
tran.setOutputProperty(OutputKeys.VERSION, "1.0");//版本//获取指定的节点集合
NodeList nodes = (NodeList) xpath.evaluate("//student[@stuId='1']",doc, XPathConstants.NODESET);
Element se= (Element) nodes.item(0);//获取第一个
Element e = (Element) se.getElementsByTagName("stuAddress").item(0);
e.setTextContent("湖北襄阳枣阳");
Result result= new StreamResult(newFile(System.getProperty("user.dir")+ "/src/com/zhanglu/xml/student.xml"));
tran.transform(newDOMSource(doc), result);
}