string字符串转xml_Java将字符串转换为XML文档和将XML文档转换为String

string字符串转xml

Sometimes while programming in java, we get String which is actually an XML and to process it, we need to convert it to XML Document (org.w3c.dom.Document). Also for debugging purpose or to send to some other function, we might need to convert Document object to String.

有时在用Java编程时,我们得到的String实际上是XML,并且要对其进行处理,我们需要将其转换为XML Document( org.w3c.dom.Document )。 同样出于调试目的或发送给其他功能,我们可能需要将Document对象转换为String。

Here I am providing two utility functions.

在这里,我提供了两个实用程序功能。

  1. Document convertStringToDocument(String xmlStr): This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion.

    Document convertStringToDocument(String xmlStr) :此方法将输入作为String,然后将其转换为DOM Document并返回。 我们将使用InputSource和StringReader进行此转换。
  2. String convertDocumentToString(Document doc): This method will take input as Document and convert it to String. We will use Transformer, StringWriter and StreamResult for this purpose.

    String convertDocumentToString(Document doc) :此方法将输入作为Document并将其转换为String。 为此,我们将使用TransformerStringWriterStreamResult
package com.journaldev.xml;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

public class StringToDocumentToString {

    public static void main(String[] args) {
        final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
                                "<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
                                "<role>Developer</role><gen>Male</gen></Emp>";
        Document doc = convertStringToDocument(xmlStr);
        
        String str = convertDocumentToString(doc);
        System.out.println(str);
    }

    private static String convertDocumentToString(Document doc) {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = tf.newTransformer();
            // below code to remove XML declaration
            // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(doc), new StreamResult(writer));
            String output = writer.getBuffer().toString();
            return output;
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        
        return null;
    }

    private static Document convertStringToDocument(String xmlStr) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder;  
        try  
        {  
            builder = factory.newDocumentBuilder();  
            Document doc = builder.parse( new InputSource( new StringReader( xmlStr ) ) ); 
            return doc;
        } catch (Exception e) {  
            e.printStackTrace();  
        } 
        return null;
    }

}

When we run above program, we get the same String output that we used to create DOM Document.

当我们在上面的程序上运行时,我们得到与用于创建DOM Document相同的String输出。

<?xml version="1.0" encoding="UTF-8"?><Emp id="1"><name>Pankaj</name><age>25</age>
<role>Developer</role><gen>Male</gen></Emp>

You can use replaceAll("\n|\r", "") to remove new line characters from String and get it in compact format.

您可以使用replaceAll("\n|\r", "")从String中删除新行字符并以紧凑格式获取它。

翻译自: https://www.journaldev.com/1237/java-convert-string-to-xml-document-and-xml-document-to-string

string字符串转xml

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值