zoukankan      html  css  js  c++  java
  • java XML解析我们到底能走多远系列(12)

    我们到底能走多远系列(12)

    扯淡:距离 我们到底能走多远系列 的阶段性目标15篇,已经很近了,100篇的最终目标还很远。

       最近,接到个面试通知,做了份笔试,大部分都是基础题目,有java的,sql的。看来下一次换工作的征途又要开始啦,哈哈。

      只记得有个简单的小题目了,把ABC,变成CBA。很简单的基础题,只是我实在记不起那个笔试题里的其他题目了。哎...

    实现:

    package code.stu.string;
    
    public class Inversion {
        
        public static void main(String[] args) {
            System.out.println(inversion("abcdefghijk"));
            
        }
        
        public static String inversion(String str){
            
            char[] chars = str.toCharArray();// String 转换成char[]
            int len = chars.length;
            int min = 0;
            int max = len - 1;
            char value;
            while(min < len/2 || max > len/2){// 对调进行到中间位置就跳出循环
                // 三步互换
                value = chars[min];
                chars[min] = chars[max];
                chars[max] = value;
                min++;
                max--;
            }
            
            return String.valueOf(chars);// char[]转换成String
        }
    }

     

    主题:

      我们对xml解析都不陌生,很多地方有涉及到它,比如:Spring,tomcat,ibatis,都有用xml。

      介绍下java解析xml的两种方式:DOM和SAX

       DOM的方式是吧整个xml文件读到内存中,进行解析。

       SAX的方式则是一步步读取每一个节点和内容而触发事件进行解析。

    两种代码调用的方式如下:其实他们的源码也值得有尽力的朋友解读啊。

      Dom:

    
    
    /**
         * 
         * @param path 配置文件路径
         * @param nodeName 节点名
         * @param nodeValue 修改成什么样value
         * @return
         * @throws Exception
         */
        public int changeConfig1(String path, String nodeName, String nodeValue) throws Exception{
            File config = new File(path);
            // 解析器工厂类
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
            // 解析器
            DocumentBuilder db = dbf.newDocumentBuilder();
            // 文档树模型Document
            Document document = db.parse(config);
            // A.通过xml文档解析
            NodeList nodeList = document.getElementsByTagName(nodeName);
            // B.将需要解析的xml文档转化为输入流,再进行解析
            //InputStream is = new FileInputStream(config);
            //Document nodeList = db.parse(is); 
    
            for (int i = 0; i < nodeList.getLength(); i++) {   
                // Element extends Node
                Element node = (Element)nodeList.item(i);
                System.out.println( node.getElementsByTagName("b").item(0).getFirstChild().getNodeValue());
                node.getElementsByTagName(nodeName).item(0).getFirstChild().setTextContent(nodeValue);
                System.out.println( node.getElementsByTagName("c").item(0).getFirstChild().getNodeValue());
            }
            // 是改动生效,网上很多代码都没有提到这步操作,我不明白他们是怎么完成修改xml的value值的。
            // 可以理解成内存中的数据已经被改了,还没有映射到文件中
            TransformerFactory tfFac = TransformerFactory.newInstance();
            Transformer tf = tfFac.newTransformer();
            DOMSource source = new DOMSource(document);
            tf.transform(source, new StreamResult(config));// 修改内容映射到文件
            return 0;
        }
     

      SAX:

    package web.method.file.sax;
    
    
    import java.io.FileReader;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.xml.sax.Attributes;
    import org.xml.sax.InputSource;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import org.xml.sax.helpers.DefaultHandler;
    import org.xml.sax.helpers.XMLReaderFactory;
    
    import web.method.file.model.People;
    // 继承DefaultHandler
    public class ConfigHandler extends DefaultHandler {
    
        private final List<People> peoples = new ArrayList<People>();
    
        private People p;
        private String currentValue = null;
        private String preTag = null;
    
        @Override
        // 开始Element
        public void startElement(String uri, String localName, String name,
                Attributes attributes) throws SAXException {
            if("people".equals(name)){
                p = new People();
            }
            preTag = name;
        }
    
        @Override
        // 结束Element
        public void endElement(String uri, String localName, String name)
                throws SAXException {
            if("people".equals(name) && p != null){
                peoples.add(p);
            }
            preTag = null;
        }
    
        @Override
        //
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            currentValue = new String(ch, start, length);
            
            if(preTag != null && p != null){
                if(preTag.equals("name")){
                    p.setName(currentValue);
                }else if(preTag.equals("from")){
                    p.setFrom(currentValue);
                }
                
            }
        }
    
        // 取值
        public List<People> getPeoples(){
            return peoples;
        }
        
        public static void main(String[] args) throws Exception {
            ConfigHandler handler = new ConfigHandler();
            
            //创建一个XML解析器(通过SAX方式读取解析XML)  
            XMLReader reader = XMLReaderFactory.createXMLReader(); //设置XML解析器的处理文档内容相关事件的处理器  
            reader.setContentHandler(handler); 
            //解析books.xml文档 
            reader.parse(new InputSource(new FileReader("D:\\我的文档\\company.xml"))); 
            
            for (int i = 0; i < handler.getPeoples().size(); i++) {
                System.out.println(handler.getPeoples().get(i).getName());
            }
        }
    }


    xml:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <company  count="3" xmlns="http://test.org/company">  
    <people>
    <name>dc</name>
    <age>96</age>
    <from>los angles</from>
    <discription>have biggest mind in the world</discription>
    </people>
    <people>
    <name>jiannanchun</name>
    <age>96</age>
    <from>las vages</from>
    <discription>a good defender</discription>
    </people>
    </company> 


    总结:这只是对解析xml的开始,先学会怎么用吧。

    为什么要继续对这方面学习呢?因为现在自己空闲的时候,在编个工程,想用xml来存数据。在这方面学习过的朋友给点建议哦。

    现在遇到的问题是:怎样设计一个多线程读取xml文件内容的结构?有想法的给点建议。

    让我们继续前行

    ----------------------------------------------------------------------

    努力不一定成功,但不努力肯定不会成功。
    共勉。

  • 相关阅读:
    Codeforces Round #313 (Div. 2) D. Equivalent Strings 解题心得
    UVA
    2015 HUAS Summer Contest#1~A
    2015 HUAS Summer Training#2~D
    2015 HUAS Summer Training#2~C
    2015 HUAS Summer Training#2~E
    2015 HUAS Summer Training#2~A
    2015 HUAS Provincial Select Contest #1
    2015 HUAS Provincial Select Contest #1~F
    2015 HUAS Provincial Select Contest #2~A
  • 原文地址:https://www.cnblogs.com/killbug/p/2745615.html
Copyright © 2011-2022 走看看