Creating a Java DOM XML parser is done using the javax.xml.parsers.DocumentBuilderFactory class. Here is an example:
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Parsing an XML file into a DOM tree using the DocumentBuilder is done like this:
try {
Document document = builder.parse(
new FileInputStream("data\\text.xml"));
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
At the top is the Document object. The Document object has a single root element, which is returned by calling getDocumentElement() like this:
Element rootElement = document.getDocumentElement();
get the children of an element
NodeList nodes = element.getChildNodes();
for(int i=0; i<nodes.getLength(); i++){
Node node = nodes.item(i);
if(node instanceof Element){
//a child element to process
Element child = (Element) node;
String attribute = child.getAttribute("width");
}
}
Now you have a needed Node, so you can create put it in map as you wish, and make need for you key. method transformer.transform(new DOMSource(document),work with any Dom node or element
Create String from Document
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(document),
new StreamResult(buffer));
String str = buffer.toString();