• 用Stax方式处理xml


    1.读取xml文件,首先用类加载器加载项目目录下的xml文件,从XMLInputFactory创建我所需要的XMLStreamReader,即得到了xml文件。根据XMLStreamConstant

    属性值,就可以操作所得到的xml文件内容,详情看以下代码。

    public class TestStax {
        public static void main(String[] args) {
            //基于光标式的
    //        new TestStax().baseStax();
    //        new TestStax().baseStax_01();
            //基于迭代模型的
    //       new TestStax().baseStax_02();
         //基于过滤器的 
         new TestStax().baseStax_03();  }
    public void baseStax(){ XMLInputFactory xif = XMLInputFactory.newInstance(); InputStream is = null; XMLStreamReader xsr = null; try { //第一种加载文件方式,此文件在根目录下 is = TestStax.class.getClassLoader().getResourceAsStream("menu.xml"); xsr = xif.createXMLStreamReader(is); while(xsr.hasNext()){ int type = xsr.next(); System.out.println(type); if(type == XMLStreamConstants.START_ELEMENT){ System.out.println(xsr.getName()); }else if(type == XMLStreamConstants.CHARACTERS){ System.out.println(xsr.getText().trim()); }else if(type == XMLStreamConstants.END_ELEMENT){ System.out.println("/" + xsr.getName()); } } } catch (Exception e) { e.printStackTrace(); }finally{ if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } public void baseStax_01(){ XMLInputFactory xif = XMLInputFactory.newInstance(); InputStream is = null; XMLStreamReader xmlsr = null; try { //另一种加载文件方式 is = new FileInputStream(System.getProperty("java.class.path") + File.separator + "menu.xml"); xmlsr = xif.createXMLStreamReader(is); while(xmlsr.hasNext()){ int type = xmlsr.next(); //XMLStreamConstants.START_ELEMENT=1 if(type == 1){ if("name".equals(xmlsr.getName().toString())){ System.out.print(xmlsr.getElementText() + ":"); }else if("price".equals(xmlsr.getName().toString())){ System.out.println(xmlsr.getElementText()); } } } } catch (Exception e) { e.printStackTrace(); }finally{ if(is != null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } public void baseStax_02(){ XMLInputFactory xif = XMLInputFactory.newInstance(); InputStream is = null;
    is
    = TestStax.class.getClassLoader().getResourceAsStream("menu.xml"); try { XMLEventReader xmler = xif.createXMLEventReader(is); while(xmler.hasNext()){ XMLEvent xmle = xmler.nextEvent(); if(xmle.isStartElement()){ String name = xmle.asStartElement().getName().toString(); if("name".equals(name)){ System.out.print(xmler.getElementText() + ":"); }else if("price".equals(name)){ System.out.println(xmler.getElementText()); } } } } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } }   public void baseStax_03(){
      XMLInputFactory xif = XMLInputFactory.newFactory();
      InputStream is = TestStax.class.getClassLoader().getResourceAsStream("menu.xml");
      XMLEventReader xmler = null;
      try {
       xmler = xif.createFilteredReader(xif.createXMLEventReader(is), new EventFilter() {
        @Override
        public boolean accept(XMLEvent event) {
         if(event.isStartElement()){
          String name = event.asStartElement().getName().toString();
          if("name".equals(name) || "price".equals(name)){
           return true;
          }
         }
         return false;
        }
       } );
      } catch (XMLStreamException e) {
       e.printStackTrace();
      }
      while(xmler.hasNext()){ 
       try {
        XMLEvent xmle = xmler.nextEvent();
        if(xmle.isStartElement()){
         String nm = xmle.asStartElement().getName().toString();
         if("name".equals(nm)){
          System.out.print(xmler.getElementText() + ":");
         }else if("price".equals(nm)){
          System.out.println(xmler.getElementText());
         }
        }
       } catch (XMLStreamException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
      }
     }

    }

     下面是我说是用的xml,在w3cSchool里弄的xml文件,也可以自己建一个xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    
     <breakfast_menu>
     <food ceshi="test">
      <name>Belgian Waffles</name> 
      <price>$5.95</price> 
      <description>two of our famous Belgian Waffles with plenty of real maple syrup</description> 
      <calories>650</calories> 
      </food>
     <food ceshi="test">
      <name>Strawberry Belgian Waffles</name> 
      <price>$7.95</price> 
      <description>light Belgian waffles covered with strawberries and whipped cream</description> 
      <calories>900</calories> 
      </food>
     <food>
      <name>Berry-Berry Belgian Waffles</name> 
      <price>$8.95</price> 
      <description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description> 
      <calories>900</calories> 
      </food>
     <food>
      <name>French Toast</name> 
      <price>$4.50</price> 
      <description>thick slices made from our homemade sourdough bread</description> 
      <calories>600</calories> 
      </food>
     <food>
      <name>Homestyle Breakfast</name> 
      <price>$6.95</price> 
      <description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description> 
      <calories>950</calories> 
      </food>
      </breakfast_menu>

     3.基于Xpath处理xml

     1     //基于Xpath
     2     public void baseStax_04(){
     3         InputStream is = null;
     4         is = TestStax.class.getClassLoader().getResourceAsStream("menu.xml");
     5         XPathFactory xpf = XPathFactory.newInstance();
     6         XPath xp = xpf.newXPath();    
     7         try {
     8             //创建文档对象
     9             DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    10             //创建文档
    11             Document doc = db.parse(is);
    12             NodeList nl = (NodeList)xp.evaluate("//food[@ceshi='test']", doc,XPathConstants.NODESET);
    13 //            for(int i=0;i<nl.getLength();i++){
    14 //                Element ele = (Element)nl.item(i);
    15 //                String value = ele.getElementsByTagName("name").item(0).getTextContent();
    16 //                System.out.println(value);
    17 //            }
    18             //当不把node转化为element时
    19             for(int j=0;j<nl.getLength();j++){
    20                 NodeList nodelist = nl.item(j).getChildNodes();
    21                 for(int p=0;p<nodelist.getLength();p++){
    22                     Node nodechild = nodelist.item(p);
    23                     if(nodechild.getNodeName() != "#text"){
    24                         System.out.println(nodechild.getNodeName() + ":" + nodechild.getTextContent());
    25                     }
    26                 }
    27             }
    28         } catch (Exception e) {
    29             e.printStackTrace();
    30         }
    31     }

     4.修改xml,用XPath计算得到查找的位置,修改后用Transformer进行替换原文件

     1 public void update_xml(){
     2         XPath xpath = XPathFactory.newInstance().newXPath();
     3         InputStream is = TestStax.class.getClassLoader().getResourceAsStream("menu.xml");
     4         Document doc= null;
     5         try {
     6             doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
     7             NodeList nodelist = (NodeList)xpath.evaluate("//food[name='Belgian']", doc,XPathConstants.NODESET );
     8             Element element = (Element)nodelist.item(0);
     9             Element ele = (Element)element.getElementsByTagName("price").item(0);
    10             System.out.println(ele.getTextContent());
    11             ele.setTextContent("12121");
    12             Transformer transformer = TransformerFactory.newInstance().newTransformer();
    13             transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
    14             Result result = new StreamResult(System.out);
    15             transformer.transform(new DOMSource(doc), result);
    16         } catch (Exception e) {
    17             e.printStackTrace();
    18         }    
    19     }

    5.以XMLStreamWriter的方式写入xml

     1 public void writeXml(){
     2         try {
     3             XMLStreamWriter xmlsw = XMLOutputFactory.newFactory().createXMLStreamWriter(System.out);
     4             xmlsw.writeStartDocument("UTF-8", "1.0");
     5             xmlsw.writeEndDocument();
     6             String ns = "http://xiaoqiaolv";
     7             xmlsw.writeStartElement("ns","student",ns);
     8             xmlsw.writeStartElement("name");
     9             xmlsw.writeAttribute("realname","zhangsan");
    10             xmlsw.writeCharacters("text");
    11             xmlsw.writeEndElement();
    12             xmlsw.writeEndElement();
    13             xmlsw.flush();
    14             xmlsw.close();
    15         } catch (Exception e) {
    16             e.printStackTrace();
    17         }
    18     }
    我很小我很弱,我在慢慢成长!
  • 相关阅读:
    页面头部出现空白,页面头部出现 隐藏字符
    使用TortoiseGit对Git版本进行分支操作
    文件夹添加右键DOS快捷入口
    android离线安装adt
    V9最新手机门户域名绑定教程。
    phpcms v9 模板标签说明整理
    CAM350 10.5移动和叠层的用法
    MOS简单应用
    c语言知识点总结-------静态区、堆、栈、常量区等
    C语言关键字—-sizeof 、typedef、const、static、register、extern、#define
  • 原文地址:https://www.cnblogs.com/lvzhanhui/p/xiaoqiaolv_stax.html
Copyright © 2020-2023  润新知