码迷,mamicode.com
首页 > 编程语言 > 详细

Java操作XML

时间:2014-05-28 16:39:26      阅读:366      评论:0      收藏:0      [点我收藏+]

标签:des   style   c   class   blog   code   

以下是我学习webService视频的学习笔记:

  1. Java类和XML之间的转换.
    1. 编排:class转换为XML
    2. 反编排:xml转换为class
  2. Java读取xml三种方式
    1. Stream
    2. Event
    3. Xpath
  3. Java中使用XMLStreamWriter写入XML
  4. Java中使用TransFormer修改XML

1.Java类和XML之间的转换.

ClassInfo.java代码:

bubuko.com,布布扣
public class ClassInfo {
    private int id;
    private String className;
    
    public ClassInfo(int id, String className) {
        super();
        this.id = id;
        this.className = className;
    }
    public ClassInfo() {
        super();
    }
    // ..省略getter/setter方法...   
}
bubuko.com,布布扣

StudentInfo.java代码:

bubuko.com,布布扣
@XmlRootElement
public class StudentInfo {
    private int id;
    private String stuName;
    private ClassInfo classInfo;
    
    public StudentInfo() {
        super();
    }
    
    public StudentInfo(int id, String stuName) {
        super();
        this.id = id;
        this.stuName = stuName;
    }
  //..省略getter/setter方法
}
bubuko.com,布布扣

编排测试方法如下:

bubuko.com,布布扣
 // 编排
 @Test
 public void test01() {
   try {
      // 使用JAXB方式编排,获取JaxbContext对象 参数为需要编排的类
       JAXBContext ctx = JAXBContext.newInstance(StudentInfo.class);
       // 通过JaxbContext对象创建编排Marshaller对象
       Marshaller marshaller = ctx.createMarshaller();
       StudentInfo student = new StudentInfo();
       student.setId(1);
       student.setStuName("张璐");
       student.setClassInfo(new ClassInfo(1, "java_1"));
       // 调用编排 参数1:编排对象, 参数2:输出流
       marshaller.marshal(student, System.out);
     } catch (JAXBException e) {
       e.printStackTrace();
     }
}
bubuko.com,布布扣

PS:获取jaxbContext对象被作为参数的类,需要加上@XmlRootElement注解.如上的StudentInfo类

 

反编排测试代码如下:

bubuko.com,布布扣
 // 反编排
 @Test
 public void test02() throws Exception{
   // 获取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());
 }
bubuko.com,布布扣

 

2.Java中读取XML

在项目的com.zhanglu.xml包中有如下booksxml文件. (来自W3CSHOOL)

bubuko.com,布布扣
<?xml version="1.0" encoding="utf-8"?>

<bookstore>

    <book category="COOKING">
        <title lang="en">Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
    </book>
    <book category="CHILDREN">
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
    <book category="WEB">
        <title lang="en">XQuery Kick Start</title>
        <author>James McGovern</author>
        <author>Per Bothner</author>
        <author>Kurt Cagle</author>
        <author>James Linn</author>
        <author>Vaidyanathan Nagarajan</author>
        <year>2003</year>
        <price>49.99</price>
    </book>
    <book category="WEB">
        <title lang="en">Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
    </book>
    
</bookstore>
bubuko.com,布布扣

Stream以光标方式读取:

bubuko.com,布布扣
// 使用Stream 光标方式
@Test
public void textReader01() throws Exception {
     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));// 输出节点
               }
          }
      }
}
bubuko.com,布布扣

Event迭代方式读取(普通迭代):

bubuko.com,布布扣
// 迭代方式 EVENT
@Test
public void textReader03() throws Exception {
      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());
          }
      }
}
bubuko.com,布布扣

Event迭代方式读取(使用过滤器来减少迭代次数):

bubuko.com,布布扣
// 迭代方式 EVENT 使用过滤器 减少迭代次数
@Test
public void textReader04() throws Exception {
      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方法
           @Override
           public boolean accept(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());
          }
      }
 }
bubuko.com,布布扣

XPath方式读取XML:

bubuko.com,布布扣
//使用Xpath 操作 
@Test
public void test01() throws Exception{
      //创建输入流
      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<nodeList.getLength();i++){
         //将节点对象转换为Element对象
         Element element=(Element)nodeList.item(i);
         System.out.println(element.getElementsByTagName("author").item(0).getTextContent());
       }
}
bubuko.com,布布扣

3.使用Java中的XMLStreamWriter写入一个XML

bubuko.com,布布扣
//使用 XMLStreamWriter 来写xml文件
@Test
public void test01() throws Exception{
      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();
}
bubuko.com,布布扣

 

4.使用TransFormer来更新XML文件

bubuko.com,布布扣
// 使用TransFormer更新xml文件
@Test
public void test() throws Exception {
    // 创建输入流
    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(new File(System.getProperty("user.dir")+ "/src/com/zhanglu/xml/student.xml"));
    tran.transform(new DOMSource(doc), result);
}
bubuko.com,布布扣

 

Java操作XML,布布扣,bubuko.com

Java操作XML

标签:des   style   c   class   blog   code   

原文地址:http://www.cnblogs.com/zhanglu-cape/p/3754917.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!