java base64写入xml
时间: 2023-10-26 12:03:44 浏览: 110
Java中写xml文件
要将Base64编码的数据写入XML文件,可以按照以下步骤进行操作:
1. 将Base64编码的数据解码为字节数组。
```java
byte[] decodedData = Base64.getDecoder().decode(base64Data);
```
2. 创建一个`Document`对象并添加根元素。
```java
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element rootElement = doc.createElement("root");
doc.appendChild(rootElement);
```
3. 创建一个子元素,将解码后的数据作为其文本内容。
```java
Element dataElement = doc.createElement("data");
dataElement.setTextContent(new String(decodedData));
rootElement.appendChild(dataElement);
```
4. 将`Document`对象写入XML文件。
```java
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
FileOutputStream fos = new FileOutputStream("output.xml");
transformer.transform(new DOMSource(doc), new StreamResult(fos));
fos.close();
```
完整代码示例:
```java
import java.io.FileOutputStream;
import java.util.Base64;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Base64ToXML {
public static void main(String[] args) throws Exception {
String base64Data = "SGVsbG8gV29ybGQh"; // Base64编码的数据
byte[] decodedData = Base64.getDecoder().decode(base64Data);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
Element rootElement = doc.createElement("root");
doc.appendChild(rootElement);
Element dataElement = doc.createElement("data");
dataElement.setTextContent(new String(decodedData));
rootElement.appendChild(dataElement);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
FileOutputStream fos = new FileOutputStream("output.xml");
transformer.transform(new DOMSource(doc), new StreamResult(fos));
fos.close();
}
}
```
执行后会生成一个名为`output.xml`的文件,内容如下:
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<data>Hello World!</data>
</root>
```
阅读全文