簡體   English   中英

如何在Java中將字符串轉換為xml?

[英]How to convert a string to a xml in java?

我有一個字符串對象“ hello world”,我需要從該字符串中創建一個帶有hello world作為文本內容的xml文件。 我嘗試了以下代碼片段

String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"></soap:Envelope>";

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   

    DocumentBuilder builder;   
    try  
    {   
        builder = factory.newDocumentBuilder();   

        // Use String reader   
        Document document = builder.parse( new InputSource(   
                new StringReader( xmlString) ) );   

        TransformerFactory tranFactory = TransformerFactory.newInstance();   
        Transformer aTransformer = tranFactory.newTransformer();   
        Source src = new DOMSource( document );   
        Result dest = new StreamResult( new File("D:\\myXML.xml" ) );   
        aTransformer.transform( src, dest );  

    } catch (Exception e)   
    {   
        // TODO Auto-generated catch block   
        e.printStackTrace();   
    }   

此代碼可以正常工作。 但是當我用“ Hello world”替換字符串時,它不起作用。 有人可以幫我嗎? 謝謝

您不能將字符串“ hello world”轉換為XML,因為它不是有效的xml文檔。 它沒有聲明,也沒有標簽。

上面的代碼不會將文本轉換為xml對象,它只會采用已經是有效xml的字符串並將其寫到文件中。

老實說,如果您只想將其寫入文件,那么xml的東西就沒有必要了。

如果您想要某種“ hello world” xml文件,則需要自己添加聲明和一些標簽。

該錯誤是因為您試圖將xmlString解析為有效的XML字符串,而不是。 例如,您的代碼可以使用以下xmlString正常運行:

String xmlString = "<hi>Hello World</hi>";

如果您有String newNode = "<node>Hello World</node>";

您可以使用

 Element node =  DocumentBuilderFactory
    .newInstance()
    .newDocumentBuilder()
    .parse(new ByteArrayInputStream(newNode.getBytes()))
    .getDocumentElement();

最簡單的解決方案是:如果它是有效的字符串(按照XML規范正確),則使用FileWriter將其寫入新文件並提供.xml擴展名。 無論如何,如果它不是有效的XML字符串,它將不會轉換

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM