Why my attribute values are not printed? - java

I am trying to print the attributes values for following xml file:
<data/>
<request/>
<type>City</type>
<query>Jaipur, India</query>
</request>
<current_condition/>
<observation_time>06:37 AM</observation_time>
<temp_C>40</temp_C>
<temp_F>104</temp_F>
<weatherCode>113</weatherCode>
<weatherIconUrl/>
<weatherDesc/>
<windspeedMiles>8</windspeedMiles>
<windspeedKmph>13</windspeedKmph>
<winddirDegree>280</winddirDegree>
<winddir16Point>W</winddir16Point>
<precipMM>0.0</precipMM>
<humidity>34</humidity>
<visibility>4</visibility>
<pressure>997</pressure>
<cloudcover>25</cloudcover>
</current_condition>
<weather/>
<date>2012-07-03</date>
<tempMaxC>46</tempMaxC>
<tempMaxF>115</tempMaxF>
<tempMinC>36</tempMinC>
<tempMinF>97</tempMinF>
<windspeedMiles>6</windspeedMiles>
<windspeedKmph>9</windspeedKmph>
<winddirection>N</winddirection>
<winddir16Point>N</winddir16Point>
<winddirDegree>7</winddirDegree>
<weatherCode>113</weatherCode>
<weatherIconUrl/>
<weatherDesc/>
<precipMM>0.0</precipMM>
</weather>
<weather/>
<date>2012-07-04</date>
<tempMaxC>46</tempMaxC>
<tempMaxF>114</tempMaxF>
<tempMinC>34</tempMinC>
<tempMinF>94</tempMinF>
<windspeedMiles>12</windspeedMiles>
<windspeedKmph>20</windspeedKmph>
<winddirection>NW</winddirection>
<winddir16Point>NW</winddir16Point>
<winddirDegree>319</winddirDegree>
<weatherCode>113</weatherCode>
<weatherIconUrl/>
<weatherDesc/>
<precipMM>0.0</precipMM>
</weather>
</data>
Following is the java code which I am using to print the attribute values:
public class WorldWeatherOnline {
public static void main (String[] args) throws IOException, ParserConfigurationException, SAXException, TransformerException {
URL url = new URL("http://free.worldweatheronline.com/feed/weather.ashx?q=jaipur,india&format=xml&num_of_days=2&key=c5774216f9120304120207");
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
printElementAttributes(doc);
}
static void printElementAttributes(Document doc)
{
NodeList nl = doc.getElementsByTagName("*");
Element e;
Node n;
NamedNodeMap nnm;
String attrname;
String attrval;
int i, len;
len = nl.getLength();
for (int j=0; j < len; j++)
{
e = (Element)nl.item(j);
System.out.println(e.getTagName() + ":");
System.out.println("check-1");
nnm = e.getAttributes();
if (nnm != null)
{
for (i=0; i<nnm.getLength(); i++)
{
System.out.println("check");
n = nnm.item(i);
attrname = n.getNodeName();
attrval = n.getNodeValue();
System.out.print(" " + attrname + " = " + attrval);
}
}
System.out.println();
}
}
Basically my NamedNodeMap nnm is null, so it isn't going inside the loop. I have used these imports:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

Your XML doesn't have any attributes. It just has elements with text contents. An element with an attribute looks like this:
<element attributeName="attribute value" />
If you want to use your current XML, you'll need to get the text values of the elements instead, and presumably store those against the element name.

Related

Concatenate Elements nodes consist of same state name into one element node

input XML file
<ContactD>
<addr>
<name>jack</name>
<street>south street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621716</pin>
</addr>
<addr>
<name>Benjamin</name>
<street>north street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621706</pin>
</addr>
<addr>
<name>Ryan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>
</ContactD>
The output should like this:
<ContactD>
<addr>
<name>jack,Benjamin</name>
<street>south street,north street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621716,621706</pin>
</addr>
<addr>
<name>Ryan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>
</ContactD>
I tried using Java code I tried to match the state element after that I don't how to concatenate those two into one
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
//import com.sun.org.apache.xml.internal.security.utils.XPathFactory;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class Jparser {
private static final String FILENAME = "books.xml";
public static void main(String[] args) {
// Instantiate the Factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// optional, but recommended
// process XML securely, avoid attacks like XML External Entities (XXE)
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// parse XML file
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(FILENAME));
// optional, but recommended
// http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root Element :" + doc.getDocumentElement().getNodeName());
System.out.println("------");
// get <staff>
NodeList list = doc.getElementsByTagName("addr");
String[] hell= new String[3];
for (int temp = 0; temp < list.getLength(); temp++) {
Node node = list.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String name = element.getElementsByTagName("name").item(0).getTextContent();
String street = element.getElementsByTagName("street").item(0).getTextContent();
hell[temp]= element.getElementsByTagName("state").item(0).getTextContent();
String country = element.getElementsByTagName("country").item(0).getTextContent();
String pin = element.getElementsByTagName("pin").item(0).getTextContent();
System.out.println("Current Element :" + node.getNodeName());
System.out.println("name : " + name);
System.out.println("street : " + street);
System.out.println("state : " + hell[temp]);
System.out.println("country : " + country);
System.out.printf("pin :"+ pin);
}
}
for (int t = 0; t < list.getLength()-1; t++) {
if(hell[t].equals(hell[t+1])) {
/////here i need to concatenate the two element nodes which has same state in one xml data what to do here!!
System.out.println("same");
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
}
I got stuck when I tried to contact that two element node which I identified as the same into one...I finished up matching those state nodes...need help for concatenation!!
input
<ContactD>
<addr>
<name>jack</name>
<street>south street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621716</pin>
</addr>
<addr>
<name>Benjamin</name>
<street>north street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621706</pin>
</addr>
<addr>
<name>Ryan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>
<addr>
<name>yan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>
</ContactD>
Expected output :
<?xml version="1.0" encoding="UTF-8" standalone="no"?><ContactD>
<addr>
<name>jack,Benjamin</name>
<street>south street,north street</street>
<state>Tamilnadu</state>
<country>India</country>
<pin>621716,621706</pin>
</addr>
<addr>
<name>Ryan,yan</name>
<street>East street</street>
<state>Kerala</state>
<country>India</country>
<pin>67322</pin>
</addr>
</ContactD>
Javacode for this concatenation is below : (sorry for too many reduntant comments and uneven code)
import java.io.File;
// j a v a 2 s .co m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
//import com.sun.org.apache.xml.internal.security.utils.XPathFactory;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import java.util.ArrayList;
import java.io.IOException;
public class Jparser {
private static final String FILENAME = "books.xml";
private static void toString(Document newDoc) throws Exception{
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
Source src = new DOMSource(newDoc);
Result dest = new StreamResult(new File("books.xml"));
aTransformer.transform(src, dest);
}
public static void main(String[] args) throws Exception {
// Instantiate the Factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// optional, but recommended
// process XML securely, avoid attacks like XML External Entities (XXE)
dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// parse XML file
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File(FILENAME));
// optional, but recommended
// http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root Element :" + doc.getDocumentElement().getNodeName());
System.out.println("------");
// get <staff>
NodeList list = doc.getElementsByTagName("addr");
//String[] hell= new String[10];
ArrayList<String> hell = new ArrayList<String>();
ArrayList<Element> Ements = new ArrayList<Element>();
for (int temp = 0; temp < list.getLength(); temp++) {
Node node = list.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
Ements.add(element);
String name = element.getElementsByTagName("name").item(0).getTextContent();
String street = element.getElementsByTagName("street").item(0).getTextContent();
hell.add(element.getElementsByTagName("state").item(0).getTextContent());
String country = element.getElementsByTagName("country").item(0).getTextContent();
String pin = element.getElementsByTagName("pin").item(0).getTextContent();
System.out.println("Current Element :" + node.getNodeName());
System.out.println("name : " + name);
System.out.println("street : " + street);
System.out.println("state : " + hell.get(temp));
System.out.println("country : " + country);
System.out.printf("pin :"+ pin);
}
}
System.out.println("The size of the ArrayList is: " + Ements.size());
// System.out.println(Ements.get(0).name);
for (int t = 0; t < Ements.size()-1; t++) {
// for(int s=1;s<Ements.size()-1;s++) {
//for(int d=1; d<list.getLength()-1;d++) {
if(hell.get(t).equals(hell.get(t+1))) {
/////here i need to concatenate the two element nodes which has same state in one xml data what to do here!!
// int z=t;
String[] he= {"name","street","state","country","pin"};
for(int a=0; a<he.length; a++) {
//System.out.printf(Ements.get[a]);
String zz0=Ements.get(t).getElementsByTagName(he[a]).item(0).getTextContent();
String zz1=Ements.get(t+1).getElementsByTagName(he[a]).item(0).getTextContent();
if(!zz0.equals(zz1)){
Ements.get(t).getElementsByTagName(he[a]).item(0).setTextContent(zz0+","+zz1);
}
//String zz=Ements.get(t).getElementsByTagName(he[a]).item(0).getTextContent()+","+Ements.get(t+1).getElementsByTagName(he[a]).item(0).getTextContent();
// Ements.get(t).getElementsByTagName(he[a]).item(0).setTextContent(zz);
// System.out.println(Ements.get(t).getElementsByTagName(he[a]).item(0).getTextContent());
}
doc.getDocumentElement().removeChild(Ements.get(t+1));
Ements.remove(t+1);
hell.remove(t+1);
System.out.println(Ements.size());
}
}
System.out.println(Ements.size());
// DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
// DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
//Document newDoc = domBuilder.newDocument();
//Element rootElement = newDoc.createElement("parent");
// NodeList toremove=doc.getDocumentElement().getChildNodes();
//for(int i=0;i<toremove.getLength();i++) {
// doc.getDocumentElement().removeChild(toremove.item(i));
//}
//doc.getDocumentElement().appendChild(Ements.get(0));
//doc.getDocumentElement().appendChild(Ements.get(1));
toString(doc);
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
}

Ignore Document Builder, SAX Error

I am reading some 100 XML file and some files don't have an end tag so I am getting an error. I want java to ignore those errors and continue with the next file.
Here is my code:
package javaapplication1;
import java.io.File;
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.*;
import static java.lang.System.*;
import org.xml.sax.SAXParseException;
public class JavaApplication1 {
public static void main(String[] args) throws Exception {
try {
System.out.println("PLEASE ENTER FOLDER NAME ");
System.out.println(" ");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
File dir = new File(s);
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
String absolutePath = dir + File.separator + children[i];
File dir1 = new File(absolutePath);
String filename2 = dir.getAbsolutePath() + File.separator + children[i];
System.out.println(filename2);
Document document1 = documentBuilder.parse(filename2);
NodeList employees1 = document1.getElementsByTagName("connection");
for (int q1 = 0; q1 < employees1.getLength(); q1++) {
Node employee = employees1.item(q1);
// Node nValue = (Node) nlList.item(0);
if (employee == null) {
break;
} else {
NamedNodeMap attribute = employee.getAttributes();
Node nodeAttr = attribute.getNamedItem("server");
nodeAttr.setTextContent("Ma.com:1531");
Node nodeAttr1 = attribute.getNamedItem("service");
Node nodeAttr2 = attribute.getNamedItem("port");
nodeAttr1.setTextContent("TS6");
nodeAttr2.setTextContent("");
Node nodeAttr3 = attribute.getNamedItem("username");
nodeAttr3.setTextContent("I_USER");
}
}
TransformerFactory transformerFactory1 = TransformerFactory.newInstance();
Transformer transformer1 = transformerFactory1.newTransformer();
DOMSource domSource1 = new DOMSource(document1);
StreamResult streamResult1 = new StreamResult(new File(filename2));
transformer1.transform(domSource1, streamResult1);
}
}
catch (Exception sae1)
{
sae1.printStackTrace();
}
//}
}
}

Java: Function that parses XML data - nothing being outputted

I'm relatively new to XML processing with Java, so expect some mistakes, but anyway...I'm trying to parse the following XML data:
http://msdn.microsoft.com/en-us/library/ms762271(v=vs.85).aspx
I would like to accomplish this using a function, where the name of the XML tag and NodeList are passed in as parameters, and it returns the content.
Thanks.
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class Files {
#SuppressWarnings("unused")
public static void main (String [] args) throws IOException, ParserConfigurationException, SAXException{
String address = "/home/leo/workspace/Test/Files/src/file.xml";
String author = "author";
String title = "title";
String genre = "genre";
String price = "price";
String publish = "publish_date";
String descr = "description";
File xmlFile = new File(address);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = factory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
System.out.println(doc.getDocumentElement().getNodeName());
NodeList n = doc.getElementsByTagName("book");
System.out.println("Number of books " + n.getLength());
getElement(author, n);
}
private static void getElement(String elementName, NodeList n){
for (int i = 0; i < n.getLength(); i++){
Node showNode = n.item(i);
Element showElement = (Element)showNode;
System.out.println(elementName + ": " +
showElement.getAttribute(elementName)
);
}
}
}
The problem is : showElement.getAttribute(elementName)
you want to get the value of a node,but getAttribute is to get the attribute of the node,you should figure out what attribute means in XML.
you can get the value like this:
private static void getElement(String elementName, NodeList n){
for (int i = 0; i < n.getLength(); i++){
Node showNode = n.item(i);
NodeList nl = showNode.getChildNodes();
for(int j=0;j<nl.getLength();j++)
{
Node nd=nl.item(j);
if(nd.getNodeName().equals(elementName))
{
System.out.println(elementName + ":" + nd.getTextContent());
}
}
}
}
}

java xml parsing dblp

this is the xml file
please how to parse the tag author example we dont know how many author for each inproceeding ?
<?xml version="1.0" encoding="ISO-8859-1"?>
<dblp>
<inproceedings mdate="2014-01-18" key="series/sci/AzzagL13">
<author>Hanane Azzag</author>
<author>Mustapha Lebbah</author>
<title>A New Way for Hierarchical and Topological Clustering.</title>
<pages>85-97</pages>
<year>2011</year>
<booktitle>EGC (best of volume)</booktitle>
<ee>http://dx.doi.org/10.1007/978-3-642-35855-5_5</ee>
<crossref>series/sci/2013-471</crossref>
<url>db/series/sci/sci471.html#AzzagL13</url>
</inproceedings>
<inproceedings mdate="2014-01-18" key="series/sci/RabatelBP13">
<author>Julien Rabatel</author>
<author>Sandra Bringay</author>
<author>Pascal Poncelet</author>
<title>Mining Sequential Patterns: A Context-Aware Approach.</title>
<pages>23-41</pages>
<year>2011</year>
<booktitle>EGC (best of volume)</booktitle>
<ee>http://dx.doi.org/10.1007/978-3-642-35855-5_2</ee>
<crossref>series/sci/2013-471</crossref>
<url>db/series/sci/sci471.html#RabatelBP13</url>
</inproceedings>
</dblp>
Use Xpath, it's fast and powerfull , these lines for your example return 5 lines
Code:
final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new FileInputStream("input.xml"));
final XPath xPath = XPathFactory.newInstance().newXPath();
final NodeList nodeList = (NodeList) xPath.compile("//author").evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
}
Displays:
Hanane Azzag
Mustapha Lebbah
Julien Rabatel
Sandra Bringay
Pascal Poncelet
Following code parse using apache digester which is commonly used while parsing in real projects. Nice one from apache community
// Updated code as per you need.
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.Rule;
import org.apache.commons.digester.Rules;
import org.xml.sax.InputSource;
public class Parsing {
public static void main(String[] args) throws Exception{
InputStream data = new FileInputStream("E:\\workspace\\trunk\\Parsing\\src\\data.xml");
byte[] b = new byte[data.available()];
// data.read(b);
Digester digester = new Digester();
//Genearting Array list while encountering dblp xpath
digester.addObjectCreate("dblp", HashMap.class);
digester.addObjectCreate("dblp/inproceedings", ArrayList.class);
//Calling add method while encountering author xpath
AuthorRule rule = new AuthorRule();
digester.addRule("dblp/inproceedings/author", rule);
digester.addRule("dblp/inproceedings/title", rule);
digester.addRule("dblp/inproceedings", rule);
HashMap parsedData = (HashMap) digester.parse(data);
Iterator<Entry<String, ArrayList>> dataItr = parsedData.entrySet().iterator();
while(dataItr.hasNext()){
Entry<String, ArrayList> entry = dataItr.next();
System.out.println("Title : " + entry.getKey() + ", Authors" + entry.getValue().toString());
}
}
private static class AuthorRule extends Rule{
String currentTitle = "";
#Override
public void body(String namespace, String name, String text)
throws Exception {
HashMap object = (HashMap) digester.peek(1);
ArrayList authors = (ArrayList) digester.peek(0);
if(name.equals("title")){
currentTitle = text;
}
else if(name.equals("author")){
authors.add(text);
}
}
#Override
public void end(String namespace, String name) throws Exception {
HashMap object = (HashMap) digester.peek(1);
ArrayList authors = (ArrayList) digester.peek(0);
if(name.equals("inproceedings")){
object.put(currentTitle, authors);
}
}
}
}
output::
Title : A New Way for Hierarchical and Topological Clustering., Authros[Hanane Azzag, Mustapha Lebbah]
Title : Mining Sequential Patterns: A Context-Aware Approach., Authros[Julien Rabatel, Sandra Bringay, Pascal Poncelet]
there are number of ways, e.g. via DOM:
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class XmlAuthorReader {
public static void main(String argv[]) {
try {
File fXmlFile = new File(<filePath>);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
NodeList nList = doc.getElementsByTagName("author");
System.out.println(nList.getLength()+ " author(s) found");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("Author: " + nNode.getTextContent());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
you can find more variants here: http://www.mkyong.com/tutorials/java-xml-tutorials/

Parsing XML into a Hashmap Java

I have some information stored in XML, and I need to parse XML and store some of the values in Hashmap.
Here is the XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<section ID="1">
<Room>Room1</Room>
<Capactiy>25</Capactiy>
<Approval_Mode>personally</Approval_Mode>
<Building>Building1</Building>
<Address>Streer, 1. Stock, links</Address>
<Room_Number>ZA0115</Room_Number>
<CoordLt>16.412094</CoordLt>
<CoordLn>48.19719</CoordLn>
</section>
<section ID="2">
<Room>Room2</Room>
<Capactiy>120</Capactiy>
<Institute>E401</Institute>
<Approval_Mode>personally</Approval_Mode>
<Building>Building2</Building>
<Address>Street 2, Building2, Stiege 7, 1.Stock</Address>
<Room_Number>AH0105</Room_Number>
<CoordLt>16.369865</CoordLt>
<CoordLn>48.199006</CoordLn>
</section>
----
I want that key be:Room1 and values: 16.412094,48.19719 (example for Section ID=1)
That is example for first section.I have more than 100 section so I would like to store key and values for every section like I explained for the first example.
Output would be:
Room1: 16.412094,48.19719;
Room2: 16.369865,48.199006;
Room3: 16,48;
.
.
.
Room100: 16,49;
Can anyone help me?
Here is my code:
import java.io.File;
import java.sql.ResultSet;
import java.util.HashMap;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
public class XML extends DefaultHandler
{
static HashMap<StringBuffer, String> hashMap;
String elementName;
StringBuffer elementValue;
private HashMap<String, String> newMap;
public static void main(String[] args)
{
DefaultHandler handler = new XML();
SAXParserFactory factory = SAXParserFactory.newInstance();
try
{
hashMap = new HashMap<StringBuffer, String>();
//out = new OutputStreamWriter(System.out, "UTF8");
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(new File("xml1.xml"), handler);
System.out.println(hashMap);
}
catch(Throwable t)
{
t.printStackTrace();
}
System.exit(0);
}
public void startElement(String namespaceURI, String sName, String qName, Attributes attrs)
throws SAXException
{
String eName = sName;
if("".equals(eName)) eName = qName;
elementName = eName;
if(attrs != null)
{
for(int i = 0; i < attrs.getLength(); i++)
{
String aName = attrs.getLocalName(i);
if("".equals(aName)) aName = attrs.getQName(i);
}
}
}
public void endElement(String namespaceURI, String sName, String qName)
throws SAXException
{
String eName = sName;
if("".equals(eName)) eName = qName;
if(eName.equals(elementName))
hashMap.put(elementValue,""+ elementName );
elementValue = null;
}
public void characters(char[] ch, int start, int length)
throws SAXException
{
String str = new String(ch, start, length);
if(elementValue == null)
elementValue = new StringBuffer(str);
else
elementValue.append(str);
}
}
With this code I don't get desired output.
output is:
Room=Room1, Capacity=25......
Assume your xml file is "c:/test.xml"
Then use the following code to read and put into a hash map in in the following format as you said
key=Roomnumber value=CoordLt,CoordLn
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.spi.DirStateFactory.Result;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class xml {
public static void main(String[] args)
{
HashMap<String,String>hMap=new HashMap<String, String>();
File file=new File("c:/test.xml");
if(file.exists())
{
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
Document document=builder.parse(file);
Element documentElement=document.getDocumentElement();
NodeList sList=documentElement.getElementsByTagName("section");
if (sList != null && sList.getLength() > 0)
{
for (int i = 0; i < sList.getLength(); i++)
{
Node node = sList.item(i);
if(node.getNodeType()==Node.ELEMENT_NODE)
{
Element e = (Element) node;
NodeList nodeList = e.getElementsByTagName("Room");
String roomName= nodeList.item(0).getChildNodes().item(0)
.getNodeValue();
nodeList = e.getElementsByTagName("CoordLt");
String coordValues= nodeList.item(0).getChildNodes().item(0)
.getNodeValue();
nodeList = e.getElementsByTagName("CoordLn");
coordValues=coordValues+","+ nodeList.item(0).getChildNodes().item(0)
.getNodeValue();
hMap.put(roomName, coordValues);
}
}
}
} catch(Exception e){
System.out.println("exception occured");
}
}else
{
System.out.println("File not exists");
}
}
}
If you transform the XML using this xslt (which can be done in Java) you get your desired output, If someone sle knows howto load in a hashmap you'll be fine.
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="no" omit-xml-declaration ="yes" />
<xsl:template match="/sections">
<xsl:apply-templates select="section"/>
</xsl:template>
<xsl:template match="section" xml:space="default">
<xsl:apply-templates select="Room"/>
<xsl:text>:</xsl:text>
<xsl:apply-templates select="CoordLt" />
<xsl:text>,</xsl:text>
<xsl:apply-templates select="CoordLn"/>
<xsl:text>;</xsl:text>
</xsl:template>
</xsl:stylesheet>

Categories

Resources