zoukankan      html  css  js  c++  java
  • XML解析器简单工厂模式

    SAX的使用

    import javax.xml.parsers.SAXParser;

    import javax.xml.parsers.SAXParserFactory;

     

    import org.xml.sax.Attributes;

    import org.xml.sax.SAXException;

    import org.xml.sax.helpers.DefaultHandler;

     

    public class SaxTest1

    {

        public static void main(String[] args) throws Exception, SAXException

        {

           //step1: 获得SAX解析器工厂实例

           SAXParserFactory factory = SAXParserFactory.newInstance();

          

           //step2: 获得SAX解析器实例

           SAXParser parser = factory.newSAXParser();

          

           //step3:开始进行解析

           parser.parse(new File("students.xml"),new MyHandler());

        }

    }

     

    class MyHandler extends DefaultHandler

    {

     

        @Override

        public void startDocument() throws SAXException

        {

           System.out.println("startDocument");

        }

     

        @Override

        public void endDocument() throws SAXException

        {

           System.out.println("endDocument");

        }

     

        @Override

        public void startElement(String uri, String localName, String qName,

               Attributes attributes) throws SAXException

        {

           System.out.println("startElement");

        }

     

        @Override

        public void endElement(String uri, String localName, String qName)

               throws SAXException

        {

           System.out.println("endElement");

        }

    }

     

    import javax.xml.parsers.SAXParser;

    import javax.xml.parsers.SAXParserFactory;

     

    import org.xml.sax.Attributes;

    import org.xml.sax.SAXException;

    import org.xml.sax.helpers.DefaultHandler;

     

    public class SaxTest2

    {

        public static void main(String[] args) throws Exception, SAXException

        {

           SAXParserFactory factory = SAXParserFactory.newInstance();

     

           SAXParser parser = factory.newSAXParser();

     

           parser.parse(new File("students.xml"), new MyHandler2());

        }

    }

     

    class MyHandler2 extends DefaultHandler

    {

        private Stack<String> stack = new Stack<String>();

     

        private String name;

     

        private String sex;

     

        private String age;

     

        @Override

        public void startElement(String uri, String localName, String qName,

               Attributes attributes) throws SAXException

        {

           stack.push(qName);

     

           for (int i = 0; i < attributes.getLength(); i++)

           {

               String attrName = attributes.getQName(i);

               String attrValue = attributes.getValue(i);

     

               System.out.println(attrName + "=" + attrValue);

           }

        }

     

        @Override

        public void characters(char[] ch, int start, int length)

               throws SAXException

        {

           String tag = stack.peek();

     

           if ("name".equals(tag))

           {

               name = new String(ch, start, length);

           }

           else if ("sex".equals(tag))

           {

               sex = new String(ch, start, length);

           }

           else if ("age".equals(tag))

           {

               age = new String(ch, start, length);

           }

        }

     

        @Override

        public void endElement(String uri, String localName, String qName)

               throws SAXException

        {

           stack.pop();

     

           if ("student".equals(qName))

           {

               System.out.println("name = " + name);

               System.out.println("sex = " + sex);

               System.out.println("age = " + age);

               System.out.println();

           }

        }

    }

     

     

    Dom的使用

    import javax.xml.parsers.DocumentBuilder;

    import javax.xml.parsers.DocumentBuilderFactory;

     

    import org.w3c.dom.Document;

    import org.w3c.dom.Element;

    import org.w3c.dom.NodeList;

     

    public class DomTest1

    {

        public static void main(String[] args) throws Exception

        {

           //step1:获得dom解析器工厂(工厂的作用是用于创建具体的解析器)

           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

          

           //step2: 获得具体的dom解析器

           DocumentBuilder db= dbf.newDocumentBuilder();

          

           //step3:解析一个xml文档,获得Document对象(根结点)

           Document doc = db.parse(new File("students.xml"));

          

           NodeList list = doc.getElementsByTagName("student");

          

           for(int i=0 ;i<list.getLength();i++)

           {

               Element elem= (Element)list.item(i);

               String name = elem.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();

               String sex = elem.getElementsByTagName("sex").item(0).getFirstChild().getNodeValue();

               Integer age = Integer.valueOf(elem.getElementsByTagName("age").item(0).getFirstChild().getNodeValue());

               System.out.println(name);

               System.out.println(sex);

               System.out.println(age.intValue());

               System.out.println("-------------------------");

           }

        }

    }

     

     

    import javax.xml.parsers.DocumentBuilder;

    import javax.xml.parsers.DocumentBuilderFactory;

     

    import org.w3c.dom.Document;

    import org.w3c.dom.Element;

    import org.w3c.dom.NamedNodeMap;

    import org.w3c.dom.Node;

    import org.w3c.dom.NodeList;

     

    public class DomTest2

    {

        public static void main(String[] args) throws Exception

        {

           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

          

           DocumentBuilder db = dbf.newDocumentBuilder();

          

           Document doc = db.parse("students.xml");

          

           System.out.println(doc.getXmlEncoding());

           System.out.println(doc.getXmlVersion());

           System.out.println(doc.getXmlStandalone());

          

           System.out.println("--------------------------");

          

           Element root = doc.getDocumentElement();

          

           System.out.println(root.getTagName());

          

           //空格也算结点

           NodeList list = root.getChildNodes();

          

           for(int i=0 ; i< list.getLength();i++)

           {

               System.out.println(list.item(i).getNodeName());

           }

          

           System.out.println("----------------------------");

          

           for(int i=0 ; i< list.getLength();i++)

           {

               Node n = list.item(i);

              

               System.out.println(n.getNodeType()+":"+n.getNodeValue());

           }

          

           System.out.println("----------------------------");

          

           for(int i=0 ; i<list.getLength();i++)

           {

               Node node = list.item(i);

              

               System.out.println(node.getTextContent());

           }

          

           System.out.println("----------------------------");

          

           NodeList nodeList = doc.getElementsByTagName("student");

          

           for(int i=0;i<nodeList.getLength();i++)

           {

               NamedNodeMap map = nodeList.item(i).getAttributes();

              

               String attrName = map.item(0).getNodeName();

     

               String attrValue = map.item(0).getNodeValue();

              

               System.out.println(attrName+"="+attrValue);

           }

          

           System.out.println("----------------------------");

        }

    }

     

     

     

    import javax.xml.parsers.DocumentBuilder;

    import javax.xml.parsers.DocumentBuilderFactory;

     

    import org.w3c.dom.Attr;

    import org.w3c.dom.Comment;

    import org.w3c.dom.Document;

    import org.w3c.dom.Element;

    import org.w3c.dom.NamedNodeMap;

    import org.w3c.dom.Node;

    import org.w3c.dom.NodeList;

     

    /**

     * 使用递归解析给定的任意一个xml文档,并把它输出到命令行上

     *

     * @author anllin

     *

     */

    public class DomTest3

    {

        public static void main(String[] args) throws Exception

        {

           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

     

           DocumentBuilder db = dbf.newDocumentBuilder();

     

           Document doc = db.parse(new File("students.xml"));

          

           parseElemnet(doc.getDocumentElement());

        }

     

        private static void parseElemnet(Element element)

        {

           String tagName = element.getNodeName();

     

           NodeList childs = element.getChildNodes();

     

            System.out.print("<" + tagName );

     

           NamedNodeMap map = element.getAttributes();

     

           if (null != map)

           {

               for (int i = 0; i < map.getLength(); i++)

               {

                  Attr attr = (Attr) map.item(i);

     

                  String attrName = attr.getName();

                  String attrValue = attr.getValue();

     

                  System.out.print(" " + attrName + "=\"" + attrValue + "\"");

               }

           }

     

           System.out.print(">");

     

           for (int i = 0; i < childs.getLength(); i++)

           {

               Node node = childs.item(i);

     

               short nodeType = node.getNodeType();

     

               if (nodeType == Node.ELEMENT_NODE)

               {

                  parseElemnet((Element) node);

               }

               else if (nodeType == Node.TEXT_NODE)

               {

                  System.out.print(node.getNodeValue());

               }

               else if (nodeType == Node.COMMENT_NODE)

               {

                  System.out.print("<!--");

                  Comment comment = (Comment) node;

     

                  String data = comment.getData();

     

                  System.out.println(data);

     

                  System.out.print("-->");

               }

           }

          

           System.out.print("</"+tagName+">");

        }

    }

     

     

    Jdom的使用

    mport org.jdom.Comment;

    import org.jdom.Document;

    import org.jdom.Element;

    import org.jdom.output.Format;

    import org.jdom.output.XMLOutputter;

     

    //jdom集成了domsax的优点

    public class JdomTest1

    {

        public static void main(String[] args) throws Exception, IOException

        {

           Document document = new Document();

          

           Comment comment = new Comment("this is my comment");

           document.addContent(comment);

          

           Element root = new Element("student");

          

           root.setAttribute("id","1");

          

           document.addContent(root);

     

           Element e1 = new Element("name");

          

           e1.addContent("张三");

          

           Element e2 = new Element("sex");

          

           e2.addContent("");

          

           Element e3 = new Element("age");

          

           e3.addContent("30");

          

           root.addContent(e1);

           root.addContent(e2);

           root.addContent(e3);

          

           Format format = Format.getPrettyFormat();

          

           format.setIndent("    ");

          

           //format.setEncoding("gbk");

          

           XMLOutputter out = new XMLOutputter(format);

          

           out.output(document,new FileOutputStream("jdom.xml"));

        }

    }

     

     

     

    import org.jdom.Document;

    import org.jdom.Element;

    import org.jdom.input.SAXBuilder;

    import org.jdom.output.Format;

    import org.jdom.output.XMLOutputter;

     

    public class JdomTest2

    {

        public static void main(String[] args) throws Exception

        {

           SAXBuilder builder = new SAXBuilder();

          

           Document doc=builder.build(new File("jdom.xml"));

          

           Element root=doc.getRootElement();

          

           System.out.println(root.getName());

          

           Element name = root.getChild("name");

          

           System.out.println(name.getValue());

          

           root.removeChild("age");

          

           XMLOutputter out= new XMLOutputter(Format.getPrettyFormat().setIndent("    "));

          

           out.output(doc,new FileOutputStream("jdom2.xml"));

        }

    }

     

     

    public class JdomTest3

    {

        public static void main(String[] args) throws Exception

        {

           //jdom可以从头至尾使用方法链

           Document doc = new Document();

     

           doc.addContent(new Element("联系人列表")

                  .setAttribute("公司", "A集团")

                  .addContent(

                         new Element("联系人")

                                .addContent(new Element("姓名").setText("张三"))

                                .addContent(new Element("公司").setText("A公司"))

                                .addContent(

                                       new Element("电话")

                                              .setText("(021)566991"))

                                .addContent(

                                       new Element("地址")

                                              .addContent(

                                                     new Element("街道")

                                                            .setText("5"))

                                              .addContent(

                                                     new Element("城市")

                                                            .setText("上海市"))

                                              .addContent(

                                                     new Element("省份")

                                                            .setText("上海")))));

     

           XMLOutputter out = new XMLOutputter(Format.getPrettyFormat().setIndent(

                  "    "));

     

           out.output(doc, new FileOutputStream("contact.xml"));

        }

    }

     

     

    import org.jdom.Document;

    import org.jdom.Element;

    import org.jdom.input.SAXBuilder;

     

    public class JdomTest4

    {

        public static void main(String[] args) throws Exception

        {

           SAXBuilder builder = new SAXBuilder();

     

           Document doc = builder.build(new File("contact.xml"));

     

           System.out.println(doc);

     

           Element root = doc.getRootElement();

     

           Element first = root.getChild("联系人");

     

           List list = first.getChildren();

     

           for (int i = 0; i < list.size(); i++)

           {

               Element elem = (Element) list.get(i);

               System.out.println(elem.getName() + ":" + elem.getText());

               if (elem.getName().equals("地址"))

               {

                  List list2 = elem.getChildren();

     

                  for (int j = 0; j < list2.size(); j++)

                  {

                      Element elem2 = (Element) list2.get(j);

                      System.out.println(elem2.getName() + ":" + elem2.getText());

                  }

               }

           }

     

           for (Iterator iter = (first.getChildren()).iterator(); iter.hasNext();)

           {

               Element elem = (Element) iter.next();

               System.out.println(elem.getName() + ":" + elem.getText());

               if (elem.getName().equals("地址"))

               {

                  for (Iterator iter2 = (elem.getChildren()).iterator(); iter2

                         .hasNext();)

                  {

                      Element elem2 = (Element) iter2.next();

                      System.out.println(elem2.getName() + ":" + elem2.getText());

                  }

               }

           }

        }

    }

     

     

     

    Dom4j的使用

    import org.dom4j.Document;

    import org.dom4j.DocumentHelper;

    import org.dom4j.Element;

    import org.dom4j.io.OutputFormat;

    import org.dom4j.io.XMLWriter;

     

    public class Dom4jTest1

    {

        public static void main(String[] args) throws Exception

        {

           /*

            * Document doc = DocumentHelper.createDocument();

            *

            * Element root = DocumentHelper.createElement("student");

            *

            * doc.setRootElement(root);

            */

     

           Element root = DocumentHelper.createElement("student");

     

           Document doc = DocumentHelper.createDocument(root);

     

           root.addAttribute("name", "anllin");

     

           Element elem1 = root.addElement("sex");

     

           elem1.addAttribute("age", "30");

     

           XMLWriter xr = new XMLWriter();

     

           xr.write(doc);

     

           OutputFormat format = new OutputFormat("    ", true);

     

           XMLWriter write = new XMLWriter(new FileOutputStream("student2.xml"),

                  format);

     

           write.write(doc);

        }

    }

     

     

    import org.dom4j.Document;

    import org.dom4j.Element;

    import org.dom4j.io.SAXReader;

     

    public class Dom4jTest2

    {

        public static void main(String[] args) throws Exception

        {

           SAXReader reader = new SAXReader();

     

           Document doc = reader.read(new File("contactList.xml"));

     

           Element root = doc.getRootElement();

     

           System.out.println(root.getName() + " : " + root.attributeValue("公司"));

     

           Element contact = root.element("联系人");

     

           System.out.println(contact.getName());

     

          

           for (Iterator iter = contact.elementIterator(); iter.hasNext();)

           {

               Element elem = (Element) iter.next();

     

               System.out.println(elem.getName() + " " + elem.getText());

               if (elem.getName().equals("地址"))

               {

                  for (Iterator iter2 = elem.elementIterator(); iter2.hasNext();)

                  {

                      Element elem2 = (Element) iter2.next();

                      System.out.println(elem2.getName() + " " + elem2.getText());

                  }

               }

           }

     

          

           List list = contact.elements();

     

           for (int i = 0; i < list.size(); i++)

           {

               Element elem = (Element) list.get(i);

               System.out.println(elem.getName() + " : " + elem.getText());

               if (elem.getName().equals("地址"))

               {

                  List list2 = elem.elements();

                  for (int j = 0; j < list2.size(); j++)

                  {

                      Element elem2 = (Element) list.get(j);

                      System.out.println(elem2.getName() + " : "

                             + elem2.getText());

                  }

               }

           }

     

        }

    }

     

     

     

    import org.dom4j.Document;

    import org.dom4j.DocumentHelper;

    import org.dom4j.Element;

    import org.dom4j.io.OutputFormat;

    import org.dom4j.io.XMLWriter;

     

    public class Dom4jTest3

    {

        public static void main(String[] args) throws Exception

        {

           //dom4j不能从头至尾使用方法链,但是可以在创建元素时使用方法链。

           Element root = DocumentHelper

           .createElement("联系人列表").addAttribute("公司", "A集团");

          

           Document doc = DocumentHelper.createDocument(root);

          

           Element contact = DocumentHelper.createElement("联系人");

          

           root.add(contact);

          

           Element name = DocumentHelper.createElement("姓名").addText("张三");

           Element company = DocumentHelper.createElement("公司").addText("A公司");

           Element phone = DocumentHelper.createElement("电话").addText("(021)6559991");

           Element address = DocumentHelper.createElement("地址");

          

           contact.add(name);

           contact.add(company);

           contact.add(phone);

           contact.add(address);

          

           Element street = DocumentHelper.createElement("街道").addText("5");

           Element city = DocumentHelper.createElement("城市").addText("上海市");

           Element porvince = DocumentHelper.createElement("省份").addText("上海");

          

           address.add(street);

           address.add(city);

           address.add(porvince);

          

           //输出到控制台

           OutputFormat format = new OutputFormat("    ", true);

           format.setEncoding("gbk");

          

           XMLWriter xr = new XMLWriter(format);

            xr.write(doc);

          

           //输出到文件中

           XMLWriter write = new XMLWriter(new FileOutputStream("contactList.xml"),

                  format);

     

           write.write(doc);

        }

    }

     

     

     

     

    简单工厂模式

    工厂类

    package com.anllin.pattern.simplefactory;

     

    public class Creator

    {

        public static Product createProduct(String str)

        {

           if("A".equals(str))

           {

               return new ConcreteProductA();

           }

           else if("B".equals(str))

           {

               return new ConcreteProductB();

           }

          

           return null;

        }

    }

     

    抽象产品类

    package com.anllin.pattern.simplefactory;

     

    public abstract class Product

    {

     

    }

     

    具体产品类

    package com.anllin.pattern.simplefactory;

     

    public class ConcreteProductA extends Product

    {

     

    }

     

    public class ConcreteProductB extends Product

    {

     

    }

     

     

    客户端

    package com.anllin.pattern.simplefactory;

     

    public class Client

    {

        public static void main(String[] args)

        {

           Product productA = Creator.createProduct("A");

          

           System.out.println(productA.getClass().getName());

          

           Product productB = Creator.createProduct("B");

          

           System.out.println(productB.getClass().getName());

        }

    }

     

     

     

     

  • 相关阅读:
    XML的语法
    dell omsa 监控,Nrpe信号量泄露
    cx_Oracle 报错 Reason: image not found
    cx_Oracle 中文乱码问题解决
    High Memory in the Linux Kernel
    使用二分法查找mobile文件中区号归属地
    mysql 导出csv
    行删除按钮功能
    vsftp 根据用户设置
    安装zabbix报错configure: error: libcurl library not found
  • 原文地址:https://www.cnblogs.com/zfc2201/p/2143755.html
Copyright © 2011-2022 走看看