如何在java中将org.w3c.dom.Element输出为字符串格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1219596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:02:42  来源:igfitidea点击:

How to I output org.w3c.dom.Element to string format in java?

javaxmldom

提问by

I have an org.w3c.dom.Elementobject passed into my method. I need to see the whole xml string including its child nodes (the whole object graph). I am looking for a method that can convert the Elementinto an xml format string that I can System.out.printlnon. Just println()on the 'Element' object won't work because toString()won't output the xml format and won't go through its child node. Is there an easy way without writing my own method to do that? Thanks.

我有一个org.w3c.dom.Element对象传递到我的方法中。我需要查看整个 xml 字符串,包括其子节点(整个对象图)。我正在寻找一种方法,可以将其Element转换为我可以使用的 xml 格式字符串System.out.println。仅println()在“元素”对象上将不起作用,因为toString()不会输出 xml 格式并且不会通过其子节点。有没有一种简单的方法而不编写我自己的方法来做到这一点?谢谢。

回答by Karl

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/

标准 JAXP API 不支持,为此我使用了 JDom 库。它具有打印机功能、格式化程序选项等。http://www.jdom.org/

回答by McDowell

Assuming you want to stick with the standard API...

假设您想坚持使用标准 API ...

You could use a DOMImplementationLS:

您可以使用DOMImplementationLS

Document document = node.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document
    .getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
String str = serializer.writeToString(node);

If the <?xml version="1.0" encoding="UTF-16"?> declaration bothers you, you could use a transformerinstead:

如果 <?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();

回答by wierob

If you have the schema of the XML or can otherwise create JAXB bindings for it, you could use the JAXB Marshaller to write to System.out:

如果您拥有 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);
    }
}

回答by Tarsem Singh

Simple 4 lines code to get Stringwithout xml-declaration(<?xml version="1.0" encoding="UTF-16"?>) from org.w3c.dom.Element

String无需 xml-declaration( <?xml version="1.0" encoding="UTF-16"?>)即可获得的简单 4 行代码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);

回答by yegor256

Try jcabi-xmlwith one liner:

用一个衬垫尝试jcabi-xml

String xml = new XMLDocument(element).toString();

回答by vtd-xml-author

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

使用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)));
        }
    }

}

回答by thunderhawk

this is what i s done in jcabi:

这是在 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();
}

and it works for me!

它对我有用!