解析xml文件

前端之家收集整理的这篇文章主要介绍了解析xml文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

带解析文档准备books.xml

<?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>

导入的类如下

import java@H_404_242@.io@H_404_242@.IOException;
import java@H_404_242@.io@H_404_242@.InputStream;

import javax@H_404_242@.xml@H_404_242@.parsers@H_404_242@.DocumentBuilder;
import javax@H_404_242@.xml@H_404_242@.parsers@H_404_242@.DocumentBuilderFactory;
import javax@H_404_242@.xml@H_404_242@.parsers@H_404_242@.ParserConfigurationException;
import javax@H_404_242@.xml@H_404_242@.stream@H_404_242@.EventFilter;
import javax@H_404_242@.xml@H_404_242@.stream@H_404_242@.FactoryConfigurationError;
import javax@H_404_242@.xml@H_404_242@.stream@H_404_242@.XMLEventReader;
import javax@H_404_242@.xml@H_404_242@.stream@H_404_242@.XMLInputFactory;
import javax@H_404_242@.xml@H_404_242@.stream@H_404_242@.XMLOutputFactory;
import javax@H_404_242@.xml@H_404_242@.stream@H_404_242@.XMLStreamConstants;
import javax@H_404_242@.xml@H_404_242@.stream@H_404_242@.XMLStreamException;
import javax@H_404_242@.xml@H_404_242@.stream@H_404_242@.XMLStreamReader;
import javax@H_404_242@.xml@H_404_242@.stream@H_404_242@.XMLStreamWriter;
import javax@H_404_242@.xml@H_404_242@.stream@H_404_242@.events@H_404_242@.XMLEvent;
import javax@H_404_242@.xml@H_404_242@.transform@H_404_242@.OutputKeys;
import javax@H_404_242@.xml@H_404_242@.transform@H_404_242@.Result;
import javax@H_404_242@.xml@H_404_242@.transform@H_404_242@.Transformer;
import javax@H_404_242@.xml@H_404_242@.transform@H_404_242@.TransformerConfigurationException;
import javax@H_404_242@.xml@H_404_242@.transform@H_404_242@.TransformerException;
import javax@H_404_242@.xml@H_404_242@.transform@H_404_242@.TransformerFactory;
import javax@H_404_242@.xml@H_404_242@.transform@H_404_242@.TransformerFactoryConfigurationError;
import javax@H_404_242@.xml@H_404_242@.transform@H_404_242@.dom@H_404_242@.DOMSource;
import javax@H_404_242@.xml@H_404_242@.transform@H_404_242@.stream@H_404_242@.StreamResult;
import javax@H_404_242@.xml@H_404_242@.xpath@H_404_242@.XPath;
import javax@H_404_242@.xml@H_404_242@.xpath@H_404_242@.XPathConstants;
import javax@H_404_242@.xml@H_404_242@.xpath@H_404_242@.XPathExpressionException;
import javax@H_404_242@.xml@H_404_242@.xpath@H_404_242@.XPathFactory;
import org@H_404_242@.junit@H_404_242@.Test;
import org@H_404_242@.w3c@H_404_242@.dom@H_404_242@.Document;
import org@H_404_242@.w3c@H_404_242@.dom@H_404_242@.Element;
import org@H_404_242@.w3c@H_404_242@.dom@H_404_242@.NodeList;
import org@H_404_242@.xml@H_404_242@.sax@H_404_242@.SAXException;

第一种方式

@Test
    public void test01() {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            XMLStreamReader reader = factory.createXMLStreamReader(is);
            while(reader.hasNext()) {
                int type = reader.next();
                //判断节点类型是否是开始或者结束或者文本节点,之后根据情况及进行处理
                if(type==XMLStreamConstants.START_ELEMENT) {
                    System.out.println(reader.getName());
                } else if(type==XMLStreamConstants.CHARACTERS) {
                    System.out.println(reader.getText().trim());
                } else if(type==XMLStreamConstants.END_ELEMENT) {
                    System.out.println("/"+reader.getName());
                }
            }
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

结果如下

bookstore
这是啥
book
这是啥
title
Everyday Italian这是啥
/title
这是啥
author
Giada De Laurentiis这是啥
/author
这是啥
year
......太长了省略一下

第二种方式

@Test
    public void test02() {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            XMLStreamReader reader = factory.createXMLStreamReader(is);
            while(reader.hasNext()) {
                int type = reader.next();
                if(type==XMLStreamConstants.START_ELEMENT) {
                    String name = reader.getName().toString();
                    if(name.equals("book")) {
                        System.out.println(reader.getAttributeName(0)+":"+reader.getAttributeValue(0));
                    }
                }
            }
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

结果

category:COOKING
category:CHILDREN
category:WEB
category:WEB

第三种方式

@Test
    public void test03() {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            XMLStreamReader reader = factory.createXMLStreamReader(is);
            while(reader.hasNext()) {
                int type = reader.next();

                if(type==XMLStreamConstants.START_ELEMENT) {
                    String name = reader.getName().toString();
                    if(name.equals("title")) {
                        System.out.print(reader.getElementText()+":");
                    }
                    if(name.equals("price")) {
                        System.out.print(reader.getElementText()+"\n");
                    }
                }
            }
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

结果

Everyday Italian:30.00
Harry Potter:29.99
XQuery Kick Start:49.99
Learning XML:39.95

第四种方式

@Test
    public void test04() {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            //基于迭代模型的操作方式
            XMLEventReader reader = factory.createXMLEventReader(is);
            int num = 0;
            while(reader.hasNext()) {
                //通过XMLEvent来获取是否是某种节点类型
                XMLEvent event = reader.nextEvent();
                if(event.isStartElement()) {
                    //通过event.asxxx转换节点
                    String name = event.asStartElement().getName().toString();
                    if(name.equals("title")) {
                        System.out.print(reader.getElementText()+":");
                    }
                    if(name.equals("price")) {
                        System.out.print(reader.getElementText()+"\n");
                    }
                }
                num++;
            }
            System.out.println(num);
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

结果

Everyday Italian:30.00
Harry Potter:29.99
XQuery Kick Start:49.99
Learning XML:39.95
85

第五种方式

@Test
    public void test05() {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            //基于Filter的过滤方式,可以有效的过滤掉不用进行操作的节点,效率会高一些
            XMLEventReader reader = factory.createFilteredReader(factory.createXMLEventReader(is),new EventFilter() {
                        @Override
                        public boolean accept(XMLEvent event) {
                            //返回true表示会显示,返回false表示不显示
                            if(event.isStartElement()) {
                                String name = event.asStartElement().getName().toString();
                                if(name.equals("title")||name.equals("price"))
                                    return true;
                            }
                            return false;
                        }
                    });
            int num = 0;
            while(reader.hasNext()) {
                //通过XMLEvent来获取是否是某种节点类型
                XMLEvent event = reader.nextEvent();
                if(event.isStartElement()) {
                    //通过event.asxxx转换节点
                    String name = event.asStartElement().getName().toString();
                    if(name.equals("title")) {
                        System.out.print(reader.getElementText()+":");
                    }
                    if(name.equals("price")) {
                        System.out.print(reader.getElementText()+"\n");
                    }
                }
                num++;
            }
            System.out.println(num);
        } catch (XMLStreamException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
Everyday Italian:30.00
Harry Potter:29.99
XQuery Kick Start:49.99
Learning XML:39.95
8

第六种方式

@Test
    public void test06() {
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            //创建文档处理对象
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            //通过DocumentBuilder创建doc的文档对象
            Document doc = db.parse(is);
            //创建XPath
            XPath xpath = XPathFactory.newInstance().newXPath();
            //第一个参数就是xpath,第二参数就是文档
            NodeList list = (NodeList)xpath.evaluate("//book[@category='WEB']",doc,XPathConstants.NODESET);
            for(int i=0;i<list.getLength();i++) {
                //遍历输出相应的结果
                Element e = (Element)list.item(i);
                System.out.println(e.getElementsByTagName("title").item(0).getTextContent());
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

结果

XQuery Kick Start Learning XML

第七种方式

@Test
    public void test07() {
        try {
            XMLStreamWriter xsw = XMLOutputFactory@H_404_242@.newInstance()@H_404_242@.createXMLStreamWriter(System@H_404_242@.out);
            xsw@H_404_242@.writeStartDocument("UTF-8","1.0");
            xsw@H_404_242@.writeEndDocument();
            String ns = "http://11:dd";
            xsw@H_404_242@.writeStartElement("nsadfsadf","person",ns);
            xsw@H_404_242@.writeStartElement(ns,"id");
            xsw@H_404_242@.writeCharacters("1");
            xsw@H_404_242@.writeEndElement();
            xsw@H_404_242@.writeEndElement();
            xsw@H_404_242@.flush();
            xsw@H_404_242@.close();
        } catch (XMLStreamException e) {
            e@H_404_242@.printStackTrace();
        } catch (FactoryConfigurationError e) {
            e@H_404_242@.printStackTrace();
        }
    }

第八种方式

@Test
    public void test08() {
        InputStream is = null;
        try {
            is = TestStax.class.getClassLoader().getResourceAsStream("books.xml");
            //创建文档处理对象
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            //通过DocumentBuilder创建doc的文档对象
            Document doc = db.parse(is);
            //创建XPath
            XPath xpath = XPathFactory.newInstance().newXPath();
            Transformer tran = TransformerFactory.newInstance().newTransformer();
            tran.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
            tran.setOutputProperty(OutputKeys.INDENT,"yes");
            //第一个参数就是xpath,第二参数就是文档
            NodeList list = (NodeList)xpath.evaluate("//book[title='Learning XML']",XPathConstants.NODESET);
            //获取price节点
            Element be = (Element)list.item(0);
            Element e = (Element)(be.getElementsByTagName("price").item(0));
            e.setTextContent("333.9");
            Result result = new StreamResult(System.out);
            //通过tranformer修改节点
            tran.transform(new DOMSource(doc),result);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerFactoryConfigurationError e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
原文链接:https://www.f2er.com/xml/294868.html

猜你在找的XML相关文章