使用W3C DOM 和 JAXP 来建立和输出DOM文档并设置文档参数的方法

本文提供了一个使用Java处理XML文件的示例代码。该代码展示了如何读取、修改并重新输出XML文档的过程,包括解析XML、设置命名空间感知、转换DOM等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void main(String[] args) {

        String url = "src/xml/example/getQuote.xml";
        try {
            // Find a parser
            DocumentBuilderFactory factory
                    = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder parser = factory.newDocumentBuilder();

            // Read the document
            Document document = parser.parse(url);

            // Modify the document
            Restructurer.processNode(document);

            // Write it out again
            TransformerFactory xformFactory
                    = TransformerFactory.newInstance();
            Transformer idTransform = xformFactory.newTransformer();
            Source input = new DOMSource(document);
            Result output = new StreamResult(System.out);
            idTransform.setOutputProperty(OutputKeys.INDENT, "yes");
            idTransform.setOutputProperty(OutputKeys.ENCODING,"GBK");
            idTransform.transform(input, output);

        } catch (SAXException e) {
            System.out.println(url + " is not well-formed.");
        } catch (IOException e) {
            System.out.println(
                    "Due to an IOException, the parser could not read " + url
                    );
        } catch (FactoryConfigurationError e) {
            System.out.println("Could not locate a factory class");
        } catch (ParserConfigurationException e) {
            System.out.println("Could not locate a JAXP parser");
        } catch (TransformerConfigurationException e) {
            System.out.println("This DOM does not support transforms.");
        } catch (TransformerException e) {
            System.out.println("Transform failed.");
        }

    }
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值