Ho un oggetto org.w3c.dom.Element
passato al mio metodo. Ho bisogno di vedere l'intera stringa xml compresi i suoi nodi figli (l'intero grafico dell'oggetto). Sto cercando un metodo che può convertire il Element
in una stringa di formato xml che posso System.out.println
su. Solo println()
sull'oggetto "Elemento" non funzionerà perché toString()
non genererà il formato xml e non passerà attraverso il suo nodo figlio. C'è un modo semplice senza scrivere il mio metodo per farlo? Grazie.Come esportare org.w3c.dom.Element in formato stringa in java?
risposta
Non supportato nell'API JAXP standard, ho utilizzato la libreria JDom per questo scopo. Ha una funzione di stampa, le opzioni di formattazione ecc http://www.jdom.org/
Supponendo che si vuole attaccare con l'API standard ...
È possibile utilizzare un DOMImplementationLS:?
Document document = node.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document
.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
String str = serializer.writeToString(node);
Se il < xml version = "1.0" encoding = "UTF-16"? > dichiarazione ti dà fastidio, è possibile utilizzare un transformer invece:
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();
Questa è la soluzione se stai ricevendo [html: null] e ti aspetteresti il codice HTML. Aggiunto questo commento in modo che google possa indicizzare la risposta, si spera. –
È ancora possibile utilizzare LSSerializer e output "UTF-8". Utilizzare invece LSOutput con StringWriter e impostare il tipo di codifica su "UTF- * 8" – ricosrealm
Funziona anche con oggetto documento w3c – thirdy
Se avete lo schema del XML o altrimenti possibile creare associazioni JAXB per esso, è possibile utilizzare il JAXB Marshaller di scrivere a 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);
}
}
semplice codice di 4 linee per ottenere String
senza xml-dichiarazione (<?xml version="1.0" encoding="UTF-16"?>
) da 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);
Prova jcabi-xml con uno di linea:
String xml = new XMLDocument(element).toString();
Con VTD-XML, è possibile passare nel cursore ed effettuare una singola chiamata getElementFragment per recuperare il segmento (come indicato con la sua lunghezza offset e) ... Di seguito è un esempio
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)));
}
}
}
questo è ciò che viene fatto in 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();
}
e funziona per me!
+1 perché non è l'intento dell'API standard org.w3c.dom. Se sono interessato a blocchi di XML come testo, di solito cerco di analizzarlo come testo con una corrispondenza regolare (se il criterio di ricerca è facilmente rappresentato come espressione regolare). –