我有一个org.w3c.dom.Element
对象传递给我的方法。我需要查看包括其子节点的整个xml字符串(整个对象图)。我正在寻找一种可以将转换Element
为xml格式字符串的方法System.out.println
。只是println()
在'Element'对象上将不起作用,因为toString()
将不会输出xml格式,也不会通过其子节点。有没有一种简单的方法而无需编写自己的方法来做到这一点?谢谢。
Answers:
假设您要坚持使用标准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”?>声明使您感到困扰,则可以使用转换器:
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();
<?xml version="1.0" encoding="UTF-16"?>
声明什么麻烦事了......我们也可以加入这一行serializer .getDomConfig().setParameter("xml-declaration", false);
中第一个解决方案....
简单的4行代码即可从中获取String
而无需xml-declaration(<?xml version="1.0" encoding="UTF-16"?>
)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);
在标准JAXP API中不支持,我为此目的使用了JDom库。它具有打印机功能,格式化程序选项等。http://www.jdom.org/
如果您具有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);
}
}
这是在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();
}
它对我有用!
使用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)));
}
}
}