Created
February 16, 2016 14:38
-
-
Save RaffaeleSgarro/f37be9078a73e7e90383 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package stackoverflow; | |
import org.w3c.dom.*; | |
import javax.xml.parsers.DocumentBuilder; | |
import javax.xml.parsers.DocumentBuilderFactory; | |
import java.io.File; | |
public class DomParser { | |
public static void main(String... args) throws Exception { | |
// File in current JVM directory | |
File file = new File("template.html"); | |
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); | |
// Don't try to fetch the DTD over internet | |
dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); | |
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); | |
Document doc = dBuilder.parse(file); | |
Finder finder = new Finder(); | |
finder.findById(doc.getDocumentElement()); | |
System.out.println(finder.el.getTextContent()); | |
} | |
private static class Finder { | |
public boolean found; | |
public Element el; | |
private void findById(Node node) { | |
if (found) | |
return; | |
NamedNodeMap attrs = node.getAttributes(); | |
if (attrs != null) { | |
Node id = attrs.getNamedItem("id"); | |
if (id != null) { | |
el = (Element) node; | |
found = true; | |
} | |
} | |
NodeList childNodes = node.getChildNodes(); | |
for (int i = 0; i < childNodes.getLength(); i++) { | |
if (found) | |
return; | |
Node child = childNodes.item(i); | |
findById(child); | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<!DOCTYPE html | |
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" | |
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> | |
<html> | |
<head> | |
<title>TEST</title> | |
</head> | |
<body> | |
<h1 id="hey">Hello, World!</h1> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment