我有一个 org.w3c.dom.Element对象传递到我的方法。我需要查看整个 xml 字符串,包括它的子节点(整个对象图)。我正在寻找一个方法,可以转换的 Element到一个 xml 格式的字符串,我可以 System.out.println上。仅仅在‘ Element’对象上使用 println()是不行的,因为 toString()不会输出 xml 格式,也不会遍历它的子节点。有没有一种简单的方法不用写我自己的方法就可以做到这一点?谢谢。
Not supported in the standard JAXP API, I used the JDom library for this purpose. It has a printer function, formatter options etc. http://www.jdom.org/
Simple 4 lines code to get Stringwithout xml-declaration (<?xml version="1.0" encoding="UTF-16"?>) from org.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);
With VTD-XML, you can pass into the cursor and make a single getElementFragment call to retrieve the segment (as denoted by its offset and length)... Below is an example
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)));
}
}
}