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();
}
}
}
Related
I want to get the value of the middle name from the below XML in JAVA.
<employee>
<emp1 name='firstName'>FNAme</emp1>
<emp1 name='middleName'>MNAme</emp1>
<emp1 name='LastName'>LNAme</emp1>
</employee>
this work for me pretty well:
java code
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 main
{
public static void main(String[] args) {
try {
File file = new File(".idea/company.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(file);
document.getDocumentElement().normalize();
System.out.println("Root Element :" + document.getDocumentElement().getNodeName());
NodeList nList = document.getElementsByTagName("employee");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("First Name : " + eElement.getElementsByTagName("firstName").item(0).getTextContent());
System.out.println("Middle Name : " + eElement.getElementsByTagName("middleName").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastName").item(0).getTextContent());
}
}
}
catch(IOException | ParserConfigurationException | SAXException e) {
System.out.println(e);
}
the xml look like this:
<?xml version="1.0"?>
<company>
<employee>
<firstName>FNAme</firstName>
<middleName>MNAme</middleName>
<lastName>LNAme</lastName>
</employee>
</company>
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class comparexmls {
public static void main(String[] argv) throws Exception {
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
NodeList list = doc.getChildNodes();
//System.out.println(doc.getChildNodes().item(2));
for (int i = 0; i < list.getLength(); i++) {
if (list.item(i) instanceof Element) {
Element root = (Element) list.item(i);
System.out.println(root.getNodeName());
break;
}
}
}
static String xmlRecords =
"<Search.UDB.OUT TraceId=\"1234\">\r\n" +
" <Response>Success</Response>\r\n" +
" <Status>\r\n" +
" <System Name=\"X\">\r\n" +
" <Code>00</Code>\r\n" +
" <Message></Message>\r\n" +
" </System>\r\n" +
" <System Name=\"Y\">\r\n" +
" <Code>00</Code>\r\n" +
" <Message></Message>\r\n" +
" </System>\r\n" +
" <System Name=\"Z\">\r\n" +
" <Code>00</Code>\r\n" +
" <Message></Message>\r\n" +
" </System>\r\n" +
" </Status>\r\n" +
" <NumberFound>1</NumberFound>\r\n" +
" <AccountList>\r\n" +
" <Account>\r\n" +
" <AccountNumber>XXXXXXXXXXXX</AccountNumber>\r\n" +
" <CorpNo>XX</CorpNo>\r\n" +
" <Name>Chandra</Name>\r\n" +
" <AddressLine1>100 MAIN ST</AddressLine1>\r\n" +
" <AddressLine2>ANYTOWN</AddressLine2>\r\n" +
" <AddressLine3> GA 123456789</AddressLine3>\r\n" +
" <Block />\r\n" +
" <Reclass />\r\n" +
" <EmbossLine4 />\r\n" +
" <Phone>1234567890</Phone>\r\n" +
" </Account>\r\n" +
" </AccountList>\r\n" +
"</Search.UDB.OUT>";
}
I am getting Search.UDB.OUT only.. How to iterate all the parent and childnodes..
Take a look at the XmlSlurper class in http://stefanfrings.de/bfUtilities/bfUtilities.zip. It's a recursive algorithm.
It reads the whole XML into a simple flat HashMap collecting all element names in the format:
Search.UDB.OUT.TraceId
Search.UDB.OUT.Response
Search.UDB.OUT.Status.System.Name
...
Source code of that class:
package de.stefanfrings.parsing;
import de.stefanfrings.container.ConvertingHashMap;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashSet;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
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.InputSource;
import org.xml.sax.SAXException;
public class XmlSlurper
{
public static ConvertingHashMap parse(String xmlDocument) throws ParserConfigurationException, SAXException, IOException
{
ConvertingHashMap targetMap=new ConvertingHashMap();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xmlDocument));
Document doc=builder.parse(is);
Element rootElement=doc.getDocumentElement();
collectData(rootElement,rootElement.getNodeName().toLowerCase(),targetMap);
return targetMap;
}
/** Collect the content of one element */
private static void collectData(Element element, String currentPath, ConvertingHashMap targetMap)
{
if (element==null)
{
return;
}
// Collect all attributes of this ode
NamedNodeMap attributes = element.getAttributes();
if (attributes!=null)
{
for (int i=0; i<attributes.getLength(); i++)
{
Attr attribute = (Attr) attributes.item(i);
String name = attribute.getLocalName();
if (name==null)
{
name = attribute.getNodeName();
}
String value = attribute.getNodeValue();
targetMap.put(currentPath+"."+name.toLowerCase(), value);
}
}
// Collect all child elements recursively
boolean hasChildren=false;
NodeList children=element.getChildNodes();
if (children!=null)
{
int count=0;
for (int i=0; i<children.getLength(); i++)
{
Node node=children.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
hasChildren=true;
Element child = (Element)children.item(i);
String name=child.getLocalName();
if (name==null)
{
name=child.getNodeName();
}
String key=currentPath+"."+name.toLowerCase();
// do we have already a children with same name?
if (targetMap.containsKey(key))
{
// duplicate the first (existing) item
if (count==0)
{
// Make a copy of the first element and all of its sub elements by inserting the number 0
Set<String> keySet = new HashSet<>();
keySet.addAll(targetMap.keySet());
for (String k:keySet)
{
if (k.equals(key) || k.startsWith(key+"."))
{
String existing=targetMap.get(k);
targetMap.put(k.replace(key,key+"0"),existing);
}
}
}
// add new item
collectData(child,key+String.valueOf(++count),targetMap);
}
else
{
collectData(child,key,targetMap);
}
}
}
}
if (!hasChildren)
{
// Get the text content
String text=element.getTextContent();
targetMap.put(currentPath, text);
}
else
{
targetMap.put(currentPath, ""); // no text
}
}
}
You may replace the ConvertingHashMap by a regular HashMap. The difference is that the ConvertingHash has methods like getInteger() and getDate().
I have two xml files as below.
Compare.xml
<?xml version="1.0"?>
<class>
<student rollno="393">
<firstname>dinkar</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>95</marks>
</student>
</class>
Reference.xml
<?xml version="1.0"?>
<class>
<student rollno="393">
<firstname>ila</firstname>
<lastname>kad</lastname>
<nickname>dinkar</nickname>
<marks>85</marks>
</student>
<student rollno="493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>vinni</nickname>
<marks>95</marks>
</student>
</class>
Now I need to compare and get the difference between these two xml files. I also need the output to be exported as a log file.
Below my code:
package DomParserDemo;
import java.io.File;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class DomParserDemo {
public static void main(String[] args){
try {
File inputFile = new File("input.txt");
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("student");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :"
+ nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Student roll no : "
+ eElement.getAttribute("rollno"));
System.out.println("First Name : "
+ eElement
.getElementsByTagName("firstname")
.item(0)
.getTextContent());
System.out.println("Last Name : "
+ eElement
.getElementsByTagName("lastname")
.item(0)
.getTextContent());
System.out.println("Nick Name : "
+ eElement
.getElementsByTagName("nickname")
.item(0)
.getTextContent());
System.out.println("Marks : "
+ eElement
.getElementsByTagName("marks")
.item(0)
.getTextContent());
}
}
FileHandler handler = new FileHandler("logfile.log");
// Add to the desired logger
Logger logger = Logger.getLogger("");
logger.addHandler(handler);
System.out.println("Log Generated Successfully...!!!");
} catch (Exception e) {
System.out.println("Log Generation Failed..!!!");
e.printStackTrace();
}
}
}
Now I can see the xml files in output with out tags and i need its difference and the output should be exported as a log file.
Kindly help me to finish this and thanks in advance.
Above Solution Worked for me with a slight change :
private static List<String> compareXMLLineByLine(File file1, File file2) throws Exception {
List<String> list1 = Files.lines(Paths.get(file1.getPath())).collect(Collectors.toList());
List<String> list2 = Files.lines(Paths.get(file2.getPath())).collect(Collectors.toList());
return list1.stream().filter(s->!list2.contains(s)).peek(s -> System.out.println("mismatched value: " + s)).collect(Collectors.toList());
}
You can use java-diff-utils:
https://code.google.com/p/java-diff-utils/wiki/SampleUsage
Thank you.
My present code:
package compare5;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.Difference;
import org.xml.sax.SAXException;
public class ComparisonTest {
final static Logger logger = Logger.getLogger(ComparisonTest.class);
public static void main(String[] args) {
File f1 = new File("D:/reference.xml");
File f2= new File("D:/comparison.xml");
File f3= new File("D:/Activity log.log");
try {
//create a new file if it doesn't
f3.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileReader fr1 = null;
FileReader fr2 = null;
try {
fr1 = new FileReader(f1);
fr2 = new FileReader(f2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
Diff diff = new Diff(fr1, fr2);
System.out.println("Similar? " + diff.similar());
System.out.println("Identical? " + diff.identical());
DetailedDiff detDiff = new DetailedDiff(diff);
List differences = detDiff.getAllDifferences();
for (Object object : differences) {
Difference difference = (Difference)object;
System.out.println("***********************");
System.out.println(difference);
System.out.println("***********************");
}
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ComparisonTest obj = new ComparisonTest();
obj.runMe("ila");
}
private void runMe(String parameter){
if(logger.isDebugEnabled()){
logger.debug("This is debug : " + parameter);
}
if(logger.isInfoEnabled()){
logger.info("This is info : " + parameter);
}
logger.warn("This is warn : " + parameter);
logger.error("This is error : " + parameter);
logger.fatal("This is fatal : " + parameter);
}
}
try this
private void compare(File file1, File file2) throws Exception {
List<String> list1 = Files.lines(Paths.get(file1.getPath())).collect(Collectors.toList());
List<String> list2 = Files.lines(Paths.get(file2.getPath())).collect(Collectors.toList());
list1.stream().filter(s -> !list2.contains(s)).peek(System.out::println).count() != 0;
list2.stream().filter(s -> !list1.contains(s)).peek(System.out::println).count() != 0;
}
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.
I have a XML file with data that is used in both my C# and Java version of a library.
Ideally I want to embed this XML file in a package in that library.
I only need to access it from within my library, so I was wondering: is that possible?
In Java, you could include the XML file itself in the JAR file. You can then use something like this:
InputStream istream = getClass().getResourceAsStream("/resource/path/to/some.xml");
And parse your InputStream as normal.
The above getResourceAsStream() looks in the current classpath, which would include the contents of any JAR files.
book.xml
<book>
<person>
<first>Kiran</first>
<last>Pai</last>
<age>22</age>
</person>
<person>
<first>Bill</first>
<last>Gates</last>
<age>46</age>
</person>
<person>
<first>Steve</first>
<last>Jobs</last>
<age>40</age>
</person>
<person>
<first>kunal</first>
<last>kumar</last>
<age>25</age>
</person>
</book>
create a xml file book.xml
made a jar file book.xml.jar and
palce it in war/web-inf/lib folder of your project..
then it will work..
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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 org.xml.sax.SAXParseException;
#SuppressWarnings("serial")
public class XMLParser extends HttpServlet {
InputStream istream =getClass().getResourceAsStream("/book.xml");
public void doGet(HttpServletRequest req, HttpServletResponse resp)throws IOException
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
try {
docBuilder = docBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Document doc = null;
try {
doc = docBuilder.parse (istream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " +
doc.getDocumentElement().getNodeName());
NodeList listOfPersons = doc.getElementsByTagName("person");
int totalPersons = listOfPersons.getLength();
System.out.println("Total no of people : " + totalPersons);
for(int s=0; s<listOfPersons.getLength() ; s++){
Node firstPersonNode = listOfPersons.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
Element firstPersonElement = (Element)firstPersonNode;
//-------
NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
Element firstNameElement = (Element)firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
System.out.println("First Name : " +
((Node)textFNList.item(0)).getNodeValue().trim());
//-------
NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
Element lastNameElement = (Element)lastNameList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
System.out.println("Last Name : " +
((Node)textLNList.item(0)).getNodeValue().trim());
//----
NodeList ageList = firstPersonElement.getElementsByTagName("age");
Element ageElement = (Element)ageList.item(0);
NodeList textAgeList = ageElement.getChildNodes();
System.out.println("Age : " +
((Node)textAgeList.item(0)).getNodeValue().trim());
//------
}//end of if clause
}//end of for loop with s var
//System.exit (0);
}//end of main
}