parse string in java xml file - java

Here is the xml file that i need to parse. I want to extract the data from the weatherDesc tag
<weather>
<date>2012-08-31</date>
<tempMaxC>33</tempMaxC>
<tempMaxF>91</tempMaxF>
<tempMinC>22</tempMinC>
<tempMinF>71</tempMinF>
<windspeedMiles>15</windspeedMiles>
<windspeedKmph>24</windspeedKmph>
<winddirection>W</winddirection>
<winddir16Point>W</winddir16Point>
<winddirDegree>260</winddirDegree>
<weatherCode>113</weatherCode>
<weatherIconUrl>
<![CDATA[
http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png
]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[ Sunny ]]>
</weatherDesc>
<precipMM>0.0</precipMM>
</weather>
Current Code:
I want it to print out the weatherDesc....in this case "Sunny"
URL url = new URL("http://free.worldweatheronline.com/feed/weather.ashx? key=14d7241962022903123108&q=Pittsburgh,pa.xml");
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
Element root = doc.getDocumentElement();
NodeList nodel = root.getChildNodes();
for (int a = 0; a < nodel.getLength(); a++) {
String weather = /////////////////????? code i dont know
System.out.println(weather);
}

You can use getElementsByTagName to get the element:
NodeList nodel = root.getElementsByTagName("weatherDesc");
if(nodel.getLength() > 0) {
Node item = nodel.item(0);
String weather = item.getTextContent();
}

Better use jaxb for any conversion between xml and java object
http://www.mkyong.com/java/jaxb-hello-world-example/

This will print values of all weatherDesc tags in the document:
NodeList nodeList = doc.getElementsByTagName("weatherDesc");
for (int i = 0; i < nodeList.getLength(); i++) {
System.out.println("Weather: " + nodeList.item(i).getNodeValue());

Related

Extracting data by tag name from xml object

Im trying to extract data from a database using xml tags but I keeping getting this error
'java.lang.String org.w3c.dom.Node.getNodeValue()' on a null object reference
Not sure why its saying the tag is null when I have a log of the string before I try to extracts the data and it looks like it should I believe.
<?xml version="1.0" ?>
<database>
<account>
<id>1</id>
<fname>john</fname>
<lname>smith</lname>
<status>1</status>
</account>
</database>
That is the output from the string which I'm trying to extract the data from and here is the code I'm using to extract it.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();;
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse (new ByteArrayInputStream(s.getBytes()));
Element docEle = dom.getDocumentElement ();
NodeList nl = docEle.getElementsByTagName("account");
Element entry = (Element)nl.item(0);
Element id = (Element)entry.getElementsByTagName("id").item(0);
Element fname= (Element)entry.getElementsByTagName("fname").item(0);
Element lname = (Element)entry.getElementsByTagName("lname").item(0);
Element status= (Element)entry.getElementsByTagName("status").item(0);
user_id = id.getFirstChild().getNodeValue();
user_fname = fname.getFirstChild().getNodeValue();
user_lname = lname.getFirstChild().getNodeValue();
user_status = status.getFirstChild().getNodeValue();
The app crashes when it try's to get the node value from the first element, any help Is appreciated and thanks in advance
You have started the <account> tag but did not end it. Change </user> to </account>
Managed to figure it out, and this would be helpful for anyone with similar issues i hope.
to be able to read the tag names from an xml string I did the following (s is the xml string variable)
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(s));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();;
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(is);
Element docEle = dom.getDocumentElement ();
NodeList nl = docEle.getChildNodes();
if (nl != null) {
int length = nl.getLength();
for (int i = 0; i < length; i++) {
if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element el = (Element) nl.item(i);
if (el.getNodeName().contains("account")) {
user_id = el.getElementsByTagName("id").item(0).getTextContent();
user_fname = el.getElementsByTagName("fname").item(0).getTextContent();
user_lname = el.getElementsByTagName("lname").item(0).getTextContent();
user_status = el.getElementsByTagName("status").item(0).getTextContent();
}
}
}
}
the user_ variables have the xml tag values

How read more XSD schemas with Xpath?

I have 2 XSD schemas first.xsd and second.xsd
In first.xsd is:
<xs:include schemaLocation="second.xsd" />
and I want read elements in second.xsd.
I have defined:
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(new FileInputStream("first.xsd"));
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList result1 = null;
result1 = (NodeList) xPath.compile("//element[#name='List']").evaluate(xmlDocument, XPathConstants.NODESET);
for (int k = 0; k < result1.getLength(); k++) {
Element ele = (Element)result1.item(k);
System.out.println(ele.getAttribute("type")); }
Problem is program didnt find element list in second.xsd.
Can I define some as this?
Document xmlDocument = builder.parse(new FileInputStream("first.xsd","second.xsd"));
Is something as LSResourceResolver but that is for validation.
Can I use it for my code?
Thank you for advices.

Android/Java XML Parsing with nodes of same name

I need some advice on how to parse XML with Java where there are multiple nodes that have the same tag. For example, if I have an XML file that looks like this:
<?xml version="1.0"?>
<TrackResponse>
<TrackInfo ID="EJ958083578US">
<TrackSummary>Your item was delivered at 8:10 am on June 1 in Wilmington DE 19801.</TrackSummary>
<TrackDetail>May 30 11:07 am NOTICE LEFT WILMINGTON DE 19801.</TrackDetail>
<TrackDetail>May 30 10:08 am ARRIVAL AT UNIT WILMINGTON DE 19850.</TrackDetail>
<TrackDetail>May 29 9:55 am ACCEPT OR PICKUP EDGEWATER NJ 07020.</TrackDetail>
</TrackInfo>
</TrackResponse>
I am able to get the "TrackSummary" but I do not know how to handle the "TrackDetail", since there is more than 1. There could be more than the 3 on that sample XML so I need a way to handle that.
So far I have this code:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xmlResponse));
Document dom = builder.parse(is);
//Get the ROOT: "TrackResponse"
Element docEle = dom.getDocumentElement();
//Get the CHILD: "TrackInfo"
NodeList nl = docEle.getElementsByTagName("TrackInfo");
String summary = "";
//Make sure we found the child node okay
if (nl != null && nl.getLength() > 0)
{
//In the event that there is more then one node, loop
for (int i = 0 ; i < nl.getLength(); i++)
{
summary = getTextValue(docEle,"TrackSummary");
Log.d("SUMMARY", summary);
}
return summary;
}
How would I handle the whole 'multiple TrackDetail nodes' ordeal? I'm new to XML parsing so I am a bit unfamiliar on how to tackle things like this.
You can try like this :
public Map getValue(Element element, String str) {
NodeList n = element.getElementsByTagName(str);
for (int i = 0; i < n.getLength(); i++) {
System.out.println(getElementValue(n.item(i)));
}
return list/MapHere;
}
If you are free to change your implementation then i would suggest you to use implementation given here.
you can collect the trackdetail in string array and when you are in XmlPullParser.END_TAG check for trackinfo tag end and then stop
You can refer below code for that.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(f);
Element root = doc.getDocumentElement();
NodeList nodeList = doc.getElementsByTagName("TrackInfo");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i); // this is node under track info
// do your stuff
}
for more information you can go through below link.
How to parse same name tag in xml using dom parser java?
It may help.

import from xml into jtable

I have written a code that can save data into xml. NOW I want to use that stored xml and import its data in a table I have in the form. the problem is: the code is with no error but the table is not field with the xml data :(
here is my code:
private void jPanel4ComponentShown(java.awt.event.ComponentEvent evt) {
// TODO add your handling code here:
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
try{
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("D:\\test.xml");
Element root = doc.getDocumentElement();
NodeList nodelist1 = root.getElementsByTagName("FrameDefinitionSection");
String[] st= new String[4];
for(int i=0;i<nodelist1.getLength();i++)
{
Node node=nodelist1.item(i);
st[0]= node.getChildNodes().item(1).getTextContent();
st[1]= node.getChildNodes().item(3).getTextContent();
st[2]= node.getChildNodes().item(5).getTextContent();
st[3]= node.getChildNodes().item(7).getTextContent();
((DefaultTableModel) jTable1.getModel()).addRow(st);
}
}
catch(Exception ex)
{
System.out.print("error");
}
}
and here is my xml file :
the table should show the nodes in this xml into fields of table but it does not work ! :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<FrameDefinitionSection>
<FrameNameAndElements>
<FrameName>here is the frame's name</FrameName>
<FrameElements>its element</FrameElements>
</FrameNameAndElements>
<FrameDefinition>
<Definition>the definition of the frame</Definition>
</FrameDefinition>
<FrameExampleSentences>
<ExampleSentences>its example as well</ExampleSentences>
</FrameExampleSentences>
</FrameDefinitionSection>
You search for nodes FrameDefinitionSection-Tags under the Root-Node, but you have to search for FrameNameAndElements-Tags
getElementsByTagName will find sub-sub-sub-tags too.
You better use this:
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("D:\\test.xml");
Element root = doc.getDocumentElement();
NodeList nodelist1 =
root.getChildNodes();
String[] st = new String[4];
for (int i = 0; i < nodelist1.getLength(); i++)
{
Node node = nodelist1.item(i);
if (node.getNodeType() == node.ENTITY_NODE) {
st[0] = node.getChildNodes().item(1).getTextContent();
st[1] = node.getChildNodes().item(3).getTextContent();
st[2] = node.getChildNodes().item(5).getTextContent();
st[3] = node.getChildNodes().item(7).getTextContent();
((DefaultTableModel) jTable1.getModel()).addRow(st);
}
}
if you write like following, nodelist1 is null.
NodeList nodelist1 = root.getElementsByTagName("FrameDefinitionSection");
So you need to change like this ,
NodeList nodelist1 = doc.getElementsByTagName("FrameDefinitionSection");

How do I resolve two nodes which have the same name but under different parents?

<PublicRecords>
<USBankruptcies>
<USBanktruptcy>...<USBankruptcy>
<CourtId>...</CourtId>
<USBanktruptcy>...<USBankruptcy>
<CourtId>...</CourtId>
</USBankruptcies>
<USTaxLiens>
<USTaxLien>...<USTaxLien>
<CourtId>...</CourtId>
<USTaxLien>...<USTaxLien>
<CourtId>...</CourtId>
</USTaxLiens>
<USLegalItems>
<USLegalItem><USLegalItem>
<CourtId></CourtId>
<USLegalItem><USLegalItem>
<CourtId></CourtId>
</USLegalItems>
</PubicRecords>
I am using a combination of doc and xpath objects to extract the attributes and node contents.
NodeList bp = doc.getElementsByTagName("USBankruptcy");
NodeList nl = doc.getElementsByTagName("CourtId");
long itrBP;
for (itrBP = 0; itrBP < bp.getLength(); itrBP++ )
{
Element docElement = (Element) bp.item(itrBP);
Element courtElement = (Element) nl.item(itrBP);
NodeList df = docElement.getElementsByTagName("DateFiled");
if(df.getLength() > 0)
{
dateFiled = nullIfBlank(((Element)df.item(0)).getFirstChild().getTextContent());
dateFiled = df.format(dateFiled);
}
But, when I say get elements of tag name CourtID, it will get all the CourtIDs, not just the ones under USBankruptcy.
Is there any way to specify the parent?
I tried NodeList nl = doc.getElementsByTagName("USBankruptcies/CourtId");
It gave me a dom error on run time.
Rather than calling the getElementsByTagName("CourtId") method on the Document, call it on the child Element (in your case, the <USBankruptcies> element).
NodeList bankruptcyNodes = doc.getElementsByTagName("USBankruptcies");
Element bankruptcyElement = (Element) bankruptcyNodes.item(0);
NodeList bankruptcyCourtNodes = bankruptcyElement.getElementsByTagName("CourtId");
// etc...
Please find the code here:
DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("test.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("*//USBankruptcies/CourtId");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i));
}

Categories

Resources