How to create an XML text node with an empty string value (in Java)

后端 未结 7 1688
温柔的废话
温柔的废话 2020-12-16 16:00

I am using a Transform object to save my XML file but it seems to drop empty text nodes. Is there any way to create (and keep) a text node with an empty string

7条回答
  •  一整个雨季
    2020-12-16 16:46

    Here is the code for what you are looking for:

    try{
        DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder=docFactory.newDocumentBuilder();
    
        //root Elements -- Response
        Document doc=docBuilder.newDocument();
        doc.setXmlStandalone(true);
        Element response=doc.createElement("Data");
        doc.appendChild(response);
    
        // Child Element -- Play
        Element hangup=doc.createElement("Type");
        response.appendChild(hangup);
    
        //Writer the content into xml file
        TransformerFactory transformerFactory=TransformerFactory.newInstance();
        Transformer transformer=transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT,"yes");
    
        DOMSource source=new DOMSource(doc);
        StreamResult result=new StreamResult(sayOut);
        //StreamResult result=new StreamResult(System.out);
    
        transformer.transform(source,result);
        logger.info("===========XML GENERATION DON FOR HANGUP============");
    
    }catch(ParserConfigurationException pce){
        logger.error(" ==============2======== ERROR IN PRASERCONFIGURATION ===================================");
        pce.printStackTrace();
    }
    

    Output Generated By It:

    
    
    
    
    

    Hope I have given right thing... although I agree with that or has no difference with respect to XML Parser.

提交回复
热议问题