2009-08-02 9 views
81

Tengo un objeto org.w3c.dom.Element pasado a mi método. Necesito ver toda la cadena xml incluyendo sus nodos secundarios (el gráfico completo del objeto). Estoy buscando un método que puede convertir el Element en una cadena de formato xml que puedo System.out.println en. Solo println() en el objeto 'Elemento' no funcionará porque toString() no generará el formato xml y no pasará por su nodo hijo. ¿Hay una manera fácil sin escribir mi propio método para hacer eso? Gracias.Cómo salgo org.w3c.dom.Element al formato de cadena en java?

Respuesta

1

No soportado en la API JAXP estándar, utilicé la biblioteca JDom para este propósito. Tiene una función de impresora, etc. opciones formateador http://www.jdom.org/

+0

+1 para que no sea la intención de la API org.w3c.dom estándar. Si estoy interesado en bloques de XML como texto, generalmente trato de analizarlo como texto con una coincidencia de expresiones regulares (si los criterios de búsqueda se representan fácilmente como expresiones regulares). –

145

Suponiendo que desea seguir con el API estándar ...

Se puede usar un DOMImplementationLS:? Si el < xml version

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

= Codificación "1.0" = "UTF-16"? > declaración le molesta, se puede utilizar una vez 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(); 
+7

Esta es la solución si obtiene [html: null] y esperaría el HTML. Agregó este comentario para que google pueda indexar la respuesta con suerte. –

+2

Aún puede usar LSSerializer y producir "UTF-8". Use LSOutput con StringWriter en su lugar y establezca el tipo de codificación en "UTF- * 8" – ricosrealm

+1

Funciona también con el objeto de documento w3c – thirdy

2

Si usted tiene el esquema del XML o de otro modo puede crear enlaces de JAXB para ello, se puede utilizar el JAXB Marshaller escribir en 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); 
    } 
} 
12

simple código de 4 líneas para conseguir Stringsin xml-declaración (<?xml version="1.0" encoding="UTF-16"?>) de 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); 
1

Trate jcabi-xml con un trazador de líneas:

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

Con VTD-XML, puede pasar en el cursor y hacer una sola llamada getElementFragment para recuperar el segmento (como se expresa por su desplazamiento y la longitud) ... A continuación se muestra un ejemplo

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("https://stackoverflow.com/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))); 
     } 
    } 

} 
0

esto es lo que se hace en 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(); 
} 

y funciona para mí!

Cuestiones relacionadas