我有一个org.w3c.dom.Element
对象传递给我的方法。我需要查看整个xml字符串,包括其子节点(整个对象图)。我正在寻找一种方法,可以将Element
转换为我可以System.out.println
的xml格式字符串。 “元素”对象上的println()
将无效,因为toString()
不会输出xml格式,也不会通过其子节点。没有编写自己的方法来做到这一点有一个简单的方法吗?感谢。
答案 0 :(得分:152)
假设你想坚持使用标准API ......
您可以使用DOMImplementationLS:
Document document = node.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document
.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
String str = serializer.writeToString(node);
如果<?xml version =“1.0”encoding =“UTF-16”?>宣言困扰你,你可以使用transformer代替:
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();
答案 1 :(得分:14)
从String
<?xml version="1.0" encoding="UTF-16"?>
而不使用xml-declaration (org.w3c.dom.Element
)的简单4行代码
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);
答案 2 :(得分: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);
}
}
答案 3 :(得分:1)
标准JAXP API不支持,我为此目的使用了JDom库。它有打印机功能,格式化程序选项等。http://www.jdom.org/
答案 4 :(得分:1)
使用一个班轮试试jcabi-xml:
String xml = new XMLDocument(element).toString();
答案 5 :(得分:0)
使用VTD-XML,您可以传入游标并进行单个getElementFragment调用以检索该段(由其偏移量和长度表示)...下面是一个示例
import com.ximpleware.*;
public class concatTest{
public static void main(String s1[]) throws Exception {
VTDGen vg= new VTDGen();
String s = "<users><user><firstName>some </firstName><lastName> one</lastName></user></users>";
vg.setDoc(s.getBytes());
vg.parse(false);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/users/user/firstName");
int i=ap.evalXPath();
if (i!=1){
long l= vn.getElementFragment();
System.out.println(" the segment is "+ vn.toString((int)l,(int)(l>>32)));
}
}
}
答案 6 :(得分:0)
这就是我在jcabi中所做的:
private String asString(Node node) {
StringWriter writer = new StringWriter();
try {
Transformer trans = TransformerFactory.newInstance().newTransformer();
// @checkstyle MultipleStringLiterals (1 line)
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.VERSION, "1.0");
if (!(node instanceof Document)) {
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
}
trans.transform(new DOMSource(node), new StreamResult(writer));
} catch (final TransformerConfigurationException ex) {
throw new IllegalStateException(ex);
} catch (final TransformerException ex) {
throw new IllegalArgumentException(ex);
}
return writer.toString();
}
它对我有用!