fork download
  1. import java.io.StringReader;
  2. import javax.xml.parsers.DocumentBuilderFactory;
  3. import javax.xml.parsers.DocumentBuilder;
  4. import org.xml.sax.InputSource;
  5. import org.w3c.dom.Document;
  6. import org.w3c.dom.Node;
  7. import org.w3c.dom.NodeList;
  8. import org.w3c.dom.ls.DOMImplementationLS;
  9. import org.w3c.dom.ls.LSSerializer;
  10.  
  11.  
  12. /* http://es.stackoverflow.com/q/21882/127 */
  13. class Ideone
  14. {
  15.  
  16. public static Document loadXMLFromString(String xml) throws Exception
  17. {
  18. xml = "<Wrapper>" + xml + "</Wrapper>";
  19. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  20. DocumentBuilder builder = factory.newDocumentBuilder();
  21. InputSource is = new InputSource(new StringReader(xml));
  22. return builder.parse(is);
  23. }
  24.  
  25.  
  26. public static void main (String[] args) throws java.lang.Exception
  27. {
  28. String texto = "<!-- quiero eliminar hasta el primer </div> -->\n<DIV id='elid'>soy la primera linea</DIV \n ><div>soy la segunda linea</div>";
  29.  
  30. //String -> doc
  31. Document doc = loadXMLFromString(texto);
  32.  
  33. //Construir el serializer y sacar la declaración XML
  34. DOMImplementationLS lsImpl = (DOMImplementationLS)doc.getImplementation().getFeature("LS", "3.0");
  35. LSSerializer lsSerializer = lsImpl.createLSSerializer();
  36. lsSerializer.getDomConfig().setParameter("xml-declaration", false);
  37.  
  38. //Bucle en todos los nodos de la raíz
  39. Node docRoot = doc.getDocumentElement();
  40. NodeList childNodes = docRoot.getChildNodes();
  41. StringBuilder sb = new StringBuilder();
  42. Boolean divEncontrado = false;
  43. for (int i = 0; i < childNodes.getLength(); i++) {
  44. if (!divEncontrado) {
  45. //Se encontró?
  46. divEncontrado = childNodes.item(i).getNodeName().equalsIgnoreCase("div");
  47. } else {
  48. //Si se encontró antes, agregarlo al StringBuilder
  49. sb.append(lsSerializer.writeToString(childNodes.item(i)));
  50. }
  51. }
  52. String resultado = sb.toString();
  53.  
  54. System.out.println(resultado);
  55. }
  56.  
  57. }
  58.  
  59.  
  60.  
Success #stdin #stdout 0.06s 321152KB
stdin
Standard input is empty
stdout
<div>soy la segunda linea</div>