问题
我有一个org.w3c.dom.Element对象传递给我的方法。我需要查看整个xml字符串,包括其子节点(整个对象图)。我正在寻找一种方法,可以将2337377070转换为x4格式的字符串,我可以422473023on。 'Element'对象的Justprintln()将不起作用,因为544374008不输出xml格式,也不会通过其子节点。有没有一种简单的方法可以不用自己的方法来做到这一点?谢谢。
#1 热门回答(148 赞)
假设你想坚持使用标准API ......
Document document = node.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document
.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
String str = serializer.writeToString(node);
如果声明困扰你,你可以使用atransformer:
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node),
new StreamResult(buffer));
String str = buffer.toString();
#2 热门回答(14 赞)
简单4行代码getStringwithout xml-declaration(<?xml version="1.0" encoding="UTF-16"?>)fromorg.w3c.dom.Element
DOMImplementationLS lsImpl = (DOMImplementationLS)node.getOwnerDocument().getImplementation().getFeature("LS", "3.0");
LSSerializer serializer = lsImpl.createLSSerializer();
serializer.getDomConfig().setParameter("xml-declaration", false); //by default its true, so set it to false to get String without xml-declaration
String str = serializer.writeToString(node);
#3 热门回答(2 赞)
如果你有XML的模式或者可以为它创建JAXB绑定,你可以使用JAXB Marshaller写入System.out:
import javax.xml.bind.*;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
@XmlRootElement
public class BoundClass {
@XmlAttribute
private String test;
@XmlElement
private int x;
public BoundClass() {}
public BoundClass(String test) {
this.test = test;
}
public static void main(String[] args) throws Exception {
JAXBContext jxbc = JAXBContext.newInstance(BoundClass.class);
Marshaller marshaller = jxbc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(new JAXBElement(new QName("root"),BoundClass.class,new Main("test")),System.out);
}
}