jaxp解析xml

因为jaxp是sun公司推出的一个解析xml的技术,所以在解析xml时,不用像dom4j一样导入jar包。jaxp用到的东西都包含在jre中。使用jaxp的局限性较大,比如不能创建一个xml文件,只能读取已有的文件。
这里简单介绍jaxp对xml的CRUD操作。

要操作的testBook.xml文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<书架>
    < id="b1">
        <书名>Book1</书名>
        <作者>auther1</作者>
        <售价>50元</售价>
    </>
    < id="b2">
        <书名>Book2</书名>
        <作者>auther2</作者>
        <售价>价格2</售价>
    </>
</书架>

增加一个新书节点。

public class Demo1 {

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

        //获取Document工厂对象
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // 创建DocumentBuilder对象
        DocumentBuilder db = dbf.newDocumentBuilder();
        // 获取目标文件,注意路径
        Document doc = db.parse("src/xml/dom/jaxp/testBook.xml");

        // 创建 书 节点
        Element ele = doc.createElement("书");
        // 设置属性
        ele.setAttribute("id", "b3");

        // 增加 书名,作者,售价 节点
        Element name = doc.createElement("书名");
        // 设置内容
        name.setTextContent("Book3");
        Element au = doc.createElement("作者");
        au.setTextContent("作者3");
        Element pr = doc.createElement("售价");
        pr.setTextContent("价格3");
        // 将3个节点挂到书的节点下
        ele.appendChild(name);
        ele.appendChild(au);
        ele.appendChild(pr);

        // 在将 书 节点 挂到根节点下
        // 得到根节点
        Element root = (Element) doc.getElementsByTagName("书架").item(0);
        // 挂载
        root.appendChild(ele);

        // 将改变的节点的xml从内存中写到磁盘中,需要转换对象,毕竟不能直接将内存输出是吧。
        // 获取转换工厂对象
        TransformerFactory tff = TransformerFactory.newInstance();
        // 获取转换对象
        Transformer tf = tff.newTransformer();
        // 将xml对象转为输出流
        tf.transform(new DOMSource(doc), new StreamResult(new FileOutputStream("src/xml/dom/jaxp/testBook.xml")));

        System.out.println("over");
    }
}

运行后,testBook.xml为

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<书架>
    < id="b1">
        <书名>Book1</书名>
        <作者>auther1</作者>
        <售价>50元</售价>
    </>
    < id="b2">
        <书名>Book2</书名>
        <作者>auther2</作者>
        <售价>价格2</售价>
    </>
    < id="b3">
        <书名>Book3</书名>
        <作者>作者3</作者>
        <售价>价格3</售价>
    </>
</书架>

修改节点:修改第三本书的售价。

public class Demo1 {

    public static void main(String[] args) throws Exception {
        // 得到目标文件的document对象
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse("src/xml/dom/jaxp/testBook.xml");

        // 得到要修改的节点
        Element ele = (Element) doc.getElementsByTagName("售价").item(2);
        ele.setTextContent("50元");


        // 将xml重新写入磁盘
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer tf = tff.newTransformer();
        tf.transform(new DOMSource(doc), new StreamResult(new FileOutputStream("src/xml/dom/jaxp/testBook.xml")));

        System.out.println("over");
    }

}

运行后xml文档为:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><书架>
    < id="b1">
        <书名>Book1</书名>
        <作者>auther1</作者>
        <售价>50元</售价>
    </>
    < id="b2">
        <书名>Book2</书名>
        <作者>auther2</作者>
        <售价>价格2</售价>
    </>
    < id="b3">
        <书名>Book3</书名>
        <作者>作者3</作者>
        <售价>50元</售价>
    </>
</书架>

删除节点:删除第三本书。

public class Demo1 {

    public static void main(String[] args) throws Exception {
        // 得到目标文件的document对象
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse("src/xml/dom/jaxp/testBook.xml");

        // 得到第二本书
        Element ele = (Element) doc.getElementsByTagName("书").item(2);
        // 删除节点
        ele.getParentNode().removeChild(ele);

        // 将xml重新写入磁盘
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer tf = tff.newTransformer();
        tf.transform(new DOMSource(doc), new StreamResult(new FileOutputStream("src/xml/dom/jaxp/testBook.xml")));

        System.out.println("over");
    }

}

运行后:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><书架>
    < id="b1">
        <书名>Book1</书名>
        <作者>auther1</作者>
        <售价>50元</售价>
    </>
    < id="b2">
        <书名>Book2</书名>
        <作者>auther2</作者>
        <售价>价格2</售价>
    </>

</书架>

读取节点:遍历节点

public class Demo1 {

    public static void main(String[] args) throws Exception {
        // 获得工厂类
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        // 获得解析对象
        DocumentBuilder db = dbf.newDocumentBuilder();

        // 解析目标文件
        Document doc = db.parse("src/xml/dom/jaxp/testBook.xml");

        // 获得目标文件的根节点
        Element root = doc.getDocumentElement();

        // 获取指定的节点
        System.out.println("-----得到书名-----");
        NodeList nodes = doc.getElementsByTagName("书名");
        for(int i = 0; i < nodes.getLength(); i++){
            Node node = nodes.item(i);
            System.out.println("第"+(i+1)+"本书的书名是:"+node.getTextContent());
        }

        // 遍历节点名
        System.out.println("-----遍历节点-----");
        list(root);

        // 获得指定属性值
        System.out.println("-----获得指定属性值-----");
        String attr = ((Element)doc.getElementsByTagName("书").item(0)).getAttribute("id");
        System.out.println("第一本书的id为:"+attr);
    }

}

运行结果:
这里写图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中解析XML可以使用Java内置的DOM解析器或者使用第三方库如JAXB或JDOM。这里我将介绍如何使用DOM解析器进行XML解析。 首先,你需要添加相关的依赖到你的项目中。在pom.xml文件中,添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>javax.xml.parsers</groupId> <artifactId>jaxp-api</artifactId> </dependency> ``` 接下来,我们创建一个XML解析的工具类。这个工具类可以使用DOM解析器来解析XML文件。 ```java import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; public class XmlParser { public void parseXml(String filePath) { try { File xmlFile = new File(filePath); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(xmlFile); // 获取根元素 Element rootElement = document.getDocumentElement(); // 获取所有子元素 NodeList nodeList = rootElement.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; // 根据标签名获取元素值 String value = element.getElementsByTagName("tag_name").item(0).getTextContent(); System.out.println(value); } } } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的代码中,我们通过DOM解析解析XML文件,并使用`getElementsByTagName`方法来获取指定标签的元素值。 最后,你可以在你的代码中实例化这个工具类,并调用`parseXml`方法来解析XML文件。 ```java public class Main { public static void main(String[] args) { XmlParser xmlParser = new XmlParser(); xmlParser.parseXml("path_to_xml_file"); } } ``` 请将`path_to_xml_file`替换为你实际的XML文件路径。这样你就可以使用DOM解析器来解析XML文件了。希望对你有所帮助!如果有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值