Hai ragione, con l'API XML standard, non c'è un buon modo - ecco un esempio (può essere bug cavalcato, ma corre, ma ho scritto molto tempo fa).
import javax.xml.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import java.io.*;
public class Proc
{
public static void main(String[] args) throws Exception
{
//Parse the input document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("in.xml"));
//Set up the transformer to write the output string
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty("indent", "yes");
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
//Find the first child node - this could be done with xpath as well
NodeList nl = doc.getDocumentElement().getChildNodes();
DOMSource source = null;
for(int x = 0;x < nl.getLength();x++)
{
Node e = nl.item(x);
if(e instanceof Element)
{
source = new DOMSource(e);
break;
}
}
//Do the transformation and output
transformer.transform(source, result);
System.out.println(sw.toString());
}
}
Sembrerebbe come si potrebbe ottenere il primo figlio semplicemente utilizzando doc.getDocumentElement(). GetFirstChild(), ma il problema è che se c'è qualche spazio tra la radice e l'elemento secondario, che creerà un nodo di testo nell'albero e otterrai quel nodo invece del nodo di elemento reale. L'output di questo programma è:
D:\home\tmp\xml>java Proc
<?xml version="1.0" encoding="UTF-8"?>
<element1>
<child attr1="blah">
<child2>blahblah</child2>
</child>
</element1>
Penso che si può sopprimere la stringa xml version se non ne hai bisogno, ma non sono sicuro su questo. Probabilmente cercherò di utilizzare una libreria XML di terze parti se possibile.
fonte
2009-03-10 21:04:09
No, voglio farlo con dom4j. Qualche suggerimento ... – user234194