import from xml into jtable - java

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");

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

Unexpected results from Java DOM getAttribute

I am having some trouble with my DOM parser for Java. I am trying to parse the entire XML document and save everything into either Strings or ArrayLists depending how it appears in the document. Right now I have run into one issue in particular. I am trying to parse the attribute of a child value of an element here:
-<Ntfctn>
<Id>161RD2521JI00XSZ</Id>
<CreDtTm>2016-01-27T13:25:21</CreDtTm>
+<Acct>
+<TxsSummry>
+<Ntry xmlns="urn:iso:std:iso:20022:tech:xsd:camt.054.001.04">
As you can see there are two elements under Ntfctn that contain attributes, Id and CreDtTm. Right now all I really need is "Id". I have already collected the credit amount earlier in my code. There are numerous "Id" tags throughout the XML so calling "Id" directly won't work.
I have tried calling the attribute in this way:
NodeList Ntfctn = doc.getElementsByTagName("Ntfctn");
for(int temp = 0; temp < MsgRcpt.getLength(); temp++){
System.out.println(Ntfctn.item(0).getAttributes());
}
But get some unexpected results
com.sun.org.apache.xerces.internal.dom.AttributeMap#2a139a55
I've tried changing the Ntfctn.get value to several numbers but none seem to pull what I am looking for. Other areas of my code have worked perfectly. I will post the entire thing below.
Please let me know the proper way for me to get the value from an attribute that has the same name across the file.
package parsing;
import java.io.File;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;
public class XMLParser
{
public static String CreDtTmS;
public static String MsgIdS;
public static String MsgRcptS;
public static String NtfctnS;
public void parseXML(){
try{
File inputFile = new File("C:\\Users\\jhamric\\Desktop\\Camt54.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList CreDtTm = doc.getElementsByTagName("CreDtTm");
for(int temp = 0; temp < CreDtTm.getLength(); temp++){
CreDtTmS = CreDtTm.item(0).getTextContent();
}
NodeList MsgId = doc.getElementsByTagName("MsgId");
for(int temp = 0; temp < MsgId.getLength(); temp++){
MsgIdS = MsgId.item(0).getTextContent();
}
NodeList MsgRcpt = doc.getElementsByTagName("MsgRcpt");
for(int temp = 0; temp < MsgRcpt.getLength(); temp++){
MsgRcptS = MsgRcpt.item(0).getTextContent();
}
NodeList Ntfctn = doc.getElementsByTagName("Ntfctn");
for(int temp = 0; temp < MsgRcpt.getLength(); temp++){
System.out.println(Ntfctn.item(0).getAttributes());
}
}catch (Exception e){
e.printStackTrace();
}
System.out.println("GrpHdr -> CreDtTm: "+CreDtTmS);
System.out.println("GrpHdr -> MsgId: "+MsgIdS);
System.out.println("GrpHdr -> MsgRcpt -> Id -> OrgId -> Othr -> Id: "+MsgRcptS);
}
}
The question was answered using help from the accepted answer below.
After trial and error this was the bit of code that worked:
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPath xPath =XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//Ntfctn/Id");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println(nodes.getLength());
for(int i = 0; i < nodes.getLength(); i++){
Element el = (Element) nodes.item(i);
System.out.println("Tag: "+ el.getNodeName());
System.out.println(el.getTextContent());
}
To refine your selection you can use xpath:
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xPath.evaluate("//Ntfctn/Id",
doc.getDocumentElement(), XPathConstants.NODESET);

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.

parse string in java xml file

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());

JAXB: Why does a value return null if I just set that value, and returns a real value when I set other values?

I have generadet a java class from a xsd schema with JAXB.
In the the Main class I have a method called recursiveNodeList(NodeList list) that just takes a node list and iterates through it recursivly to get all values out of it.
Everything works except one thing that I cannot simply understand.
In the code below I have these two lines:
item.setNote("Notetest1");
item.setTitle("Title1");
When I run the code I get this output:
title->#text->Title1
note->#text->Notetest1
If I just use one of the lines, like:
item.setNote("Notetest1");
// item.setTitle("Title1"); /*commented out*/
I get this output:
item->note->null
Why is the note null if I just set that value and not call setTitle() and why does it have a value when I call both setNote and setTitle?
The code in its whole:
public class JavaXML {
public static void main(String[] args) throws ParserConfigurationException, JAXBException, FileNotFoundException {
Item item = new Item();
JAXBContext jaxb = JAXBContext.newInstance(item.getClass().getPackage().getName());
Marshaller marshaller = jaxb.createMarshaller();
item.setNote("Notetest1");
item.setTitle("Title1");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
marshaller.marshal(item, doc);
NodeList nodeList = doc.getChildNodes();
recursiveNodeList(nodeList);
}
public static void recursiveNodeList(NodeList nodeList) {
for(int i = 0; i< nodeList.getLength(); i++) {
Node fstNode = nodeList.item(i);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
if(fstElmnt.getChildNodes().getLength() > 1) {
NodeList fstNmElmntLst = fstElmnt.getChildNodes();
recursiveNodeList(fstNmElmntLst);
} else {
NodeList fstNmElmntLst = fstElmnt.getChildNodes();
if(((Node)fstNmElmntLst.item(0)) != null)
System.out.println(fstNode.getNodeName()+"->"+((Node)fstNmElmntLst.item(0)).getNodeName() + "->"+((Node)fstNmElmntLst.item(0)).getNodeValue());
}
}
}
}
}
EDIT
Another question:
If I instead of setting the title and note, set the category like this:
Category category = new Category();
category.setStringOne("string1");
category.setStringTwo("string2");
item.setCategory(category);
Then the output would be:
item->category->string1string2
Is there any way to get the "string1" and "string2" values into separate variables without using string manipulation techniques?
The error is in your recursiveNodeList method. In the single element case you were hitting the System.out.println line with an Element node, and in the two element case you were hitting the System.out.println line with a Text node. The code below will work, but probably needs cleaned up.
public static void recursiveNodeList(NodeList nodeList) {
for(int i = 0; i< nodeList.getLength(); i++) {
Node fstNode = nodeList.item(i);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
if(fstElmnt.getChildNodes().getLength() > 1) {
NodeList fstNmElmntLst = fstElmnt.getChildNodes();
recursiveNodeList(fstNmElmntLst);
} else {
NodeList fstNmElmntLst = fstElmnt.getChildNodes();
Node node = fstNmElmntLst.item(0);
if(node != null)
if(node.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(fstNode.getNodeName()+"->"+node.getNodeName() + "->"+((Element)node).getTextContent());
} else {
System.out.println(fstNode.getNodeName()+"->"+node.getNodeName() + "->"+node.getNodeValue());
}
}
}
}
}
}
UPDATE
Your JAXB (JSR-222) implementation is creating the document correctly. The original and updated errors you are seeing are due to the way you are processing the DOM nodes in recursiveNodeList. If you are interested in continuing with that approach I would recommend stepping through the code and paying attention to when the current node corresponds to a tag (i.e. note) and is of type Element, and when it corresponds to text (i.e. Notetest1) and is of type Text. Below I have given a new code example that uses XPath to introspect the document which you may find easier to use.
package forum9698306;
import javax.xml.bind.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
public class JavaXML {
public static void main(String[] args) throws Exception {
Item item = new Item();
JAXBContext jaxb = JAXBContext.newInstance(item.getClass().getPackage().getName());
Marshaller marshaller = jaxb.createMarshaller();
item.setNote("Notetest1");
item.setTitle("Title1");
Category category = new Category();
category.setStringOne("string1");
category.setStringTwo("string2");
item.setCategory(category);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.newDocument();
marshaller.marshal(item, doc);
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
System.out.println(xpath.evaluate("item/note/text()", doc, XPathConstants.STRING));
System.out.println(xpath.evaluate("item/title/text()", doc, XPathConstants.STRING));
System.out.println(xpath.evaluate("item/category/stringOne/text()", doc, XPathConstants.STRING));
System.out.println(xpath.evaluate("item/category/stringTwo/text()", doc, XPathConstants.STRING));
}
}
Output
Notetest1
Title1
string1
string2

Categories

Resources