• 每日日报


    Dom解析

    ① 把整个文档先加载到内存中-> Document  所以可以对文档进行修改
    ② 如果文件比较大 可能会导致内存溢出
    编程思路 DocumentBuilderFactory->DocumentBuilder->Document->通过节点获得NodeList->具体的Node
    如果想修改 TransformerFactory->Transformer->transform(Souce, result)
    public class DomParseTest {
    2.    
    3.    @Test
    4.    public void domParse() throws Exception{
    5.        //获取DocumentBuilderFactory
    6.        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    7.        //获取DocumentBuilder
    8.        DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
    9.        //通过documentBuilder 解析xml文档获得Document对象
    10.        Document document = documentBuilder.parse("book.xml");
    11.        //通过元素的名字可以找到元素的集合
    12.        NodeList nodeList = document.getElementsByTagName("售价");
    13.        //nodeList.getLength();
    14.        for(int i = 0;i<nodeList.getLength();i++){
    15.            Node node = nodeList.item(i);
    16.            String content = node.getTextContent();
    17.            System.out.println(content);
    18.        }
    19.        //找到第二个元素
    20.        Node node = nodeList.item(0);
    21.        //读出对应节点的文本内容
    22.        String content = node.getTextContent();
    23.        System.out.println(content);
    24.    }
    25.
    26.    @Test
    27.    public void domModifyxml() throws Exception{
    28.        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    29.        DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
    30.        Document document = builder.parse("book.xml");
    31.        NodeList nodeList = document.getElementsByTagName("售价");
    32.        Node node = nodeList.item(1);
    33.        //修改节点的内容
    34.        node.setTextContent("199.00元");
    35.        
    36.        TransformerFactory transformerFactory = TransformerFactory.newInstance();
    37.        Transformer transformer = transformerFactory.newTransformer();
    38.        //数据源
    39.        Source xmlSource = new DOMSource(document);
    40.        //要输出到的目的地
    41.        Result outputTarget = new StreamResult("book.xml");
    42.        transformer.transform(xmlSource, outputTarget);
    43.    }
    44.}
  • 相关阅读:
    清源CPM代码复现
    图像分类模型
    分享-微软亚洲研究院:NLP将迎来黄金十年
    表格生成本文-代码实践-data2text-plan-py
    了解一下BigBird
    《BERT模型精讲》徐路
    精读论文的步骤
    使用预训练编码器生成文本摘要
    Heap/Perm space
    静态代码块,代码块
  • 原文地址:https://www.cnblogs.com/zhukaile/p/14833156.html
Copyright © 2020-2023  润新知