共計 1167 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。
在 Java 中,輸出一個 Document 對象,可以使用以下方法:
- 使用 DOM 方式輸出:可以使用 Transformer 類將 Document 對象轉(zhuǎn)換為字符串輸出。
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
// Assume doc is the Document object
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
- 使用 JAXB(Java Architecture for XML Binding)方式輸出:可以使用 JAXB 提供的 Marshaller 類將 Document 對象轉(zhuǎn)換為字符串輸出。
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamResult;
// Assume doc is the Document object
JAXBContext jaxbContext = JAXBContext.newInstance(Document.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(doc, new StreamResult(System.out));
- 使用 JDOM(Java-based Document Object Model)方式輸出:可以使用 JDOM 提供的 XMLOutputter 類將 Document 對象轉(zhuǎn)換為字符串輸出。
import org.jdom2.output.XMLOutputter;
// Assume doc is the Document object
XMLOutputter outputter = new XMLOutputter();
outputter.output(doc, System.out);
這些方法可以將一個 Document 對象輸出為字符串形式,可以根據(jù)具體需求選擇使用哪種方法。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完