使用DOM生成xml文件时,将节点转换成字符串

使用DOM生成xml字符串时,碰到过将部分节点转成字符串再进行摘要的过程,那么怎么将部分节点转成字符串呢?

//实例化DocumentBuilderFactory对象
        final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        //实例化DocumentBuilder对象
        final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        //实例化Document对象
        final Document document = documentBuilder.newDocument();
        //创建多个节点
        final Element rootElement = document.createElement("ROOT");
        final Element requestElement = document.createElement("REQUEST");
        final Element paramElement = document.createElement("PARAM");
        final Element param2Element = document.createElement("PARAM");
        final Element baseElement = document.createElement("BASE");
        final Element appidElement = document.createElement("APPID");
        final Element versionElement = document.createElement("VERSION");
        final Element securityElement = document.createElement("SECURITY");

        //第一个PARAM节点添加属性和值
        paramElement.setAttribute("NAME","CHANNELNO");
        paramElement.setTextContent(channelNo);
        //第二个PARAM节点添加属性和值
        param2Element.setAttribute("NAME","CHECKCODE");
        param2Element.setTextContent(null);
        //REQUEST节点添加两个PARAM节点,并按顺序添加
        requestElement.appendChild(paramElement);
        requestElement.appendChild(param2Element);
        requestElement.insertBefore(paramElement,param2Element);

        //DOCUMENT生成格式
        document.appendChild(requestElement);

        //实例化TransformerFactory对象
        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        //实例化Transformer对象
        final Transformer transformer = transformerFactory.newTransformer();

        //创建一个输出流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        //将DOCUMENT转换成输出流
        transformer.transform(new DOMSource(document),new StreamResult(bos));

        //将输出流转成String
        final String requestStr = bos.toString();
其中,transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes")这个操作可以将头不显示。如此就可以将节点转成字符串了

你可能感兴趣的:(xml)