Difficulty in parsing xml using DOM Parser - java

How to get the values of the name tag which is nested under the grouped tag below. I am able to get the values of the name nested under column tag. How to get the nested values of name coming under grouped tag.The attributes of name tag coming under grouped tag is different.
<Services>
<Service name="check" regrx="" reverseExtention="" >
<File rootProfile="Test" extension="txt" seperator="," targetSeperator="q12">
<Columns>
<name id="1" usn="2234" dob="030395" age="55" validity="20" />
<name id="2" usn="I_TWO" dob="true" age="10" validity="44" >
<grouped>
<name id="343" value1="TYPE0" value2="TYPE4" type="" value7="1"></name>
<name id="564" value1="TYPE6" value2="TYPE7" type="" value7="0"></name>
</grouped>
</name>
<name id="3" usn="55453" dob="050584" age="35" validity="123"/>
<name id="5" usn="7565" dob="050488" age="44" validity="55"/>
</Columns>
</File>
</Service>
</Services>
Here is my code below
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
File fXmlFile = new File("D://test3.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nodeList0 = doc.getElementsByTagName("Service");
NodeList nodeList1 = doc.getElementsByTagName("File");
NodeList nodeList2 = doc.getElementsByTagName("name");
NodeList nodeList3= doc.getElementsByTagName("grouped");
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
for (int temp0 = 0; temp0 < nodeList0.getLength(); temp0++) {
Node node0 = nodeList0.item(temp0);
System.out.println("\nElement type :" + node0.getNodeName());
Element Service = (Element) node0;
System.out.println("----" + temp0 + "-------");
if (node0.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("Name : " + Service.getAttribute("name"));
System.out.println("regrx : " + Service.getAttribute("regrx"));
System.out.println("reverex"+Service.getAttribute("reverseExtention"));
for (int temp = 0; temp < nodeList1.getLength(); temp++) {
Node node1 = nodeList1.item(temp);
System.out.println("------file" + temp + "--------");
System.out.println("\nElement type :" + node1.getNodeName());
Element File = (Element) node1;
//used for getting file level
if (node1.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("rootProfile:" + File.getAttribute("rootProfile"));
System.out.println("extension : " + File.getAttribute("extension"));
System.out.println("seperator : " + File.getAttribute("seperator"));
System.out.println("targetSeperator : " + File.getAttribute("targetSeperator"));
for(int temp2=0;temp2<nodeList2.getLength();temp2++){
Node node2 = nodeList2.item(temp2);
Element name = (Element) node2;
if (node2.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("id:" + name.getAttribute("id"));
System.out.println("usn : " + name.getAttribute("usn"));
System.out.println("dob : " + name.getAttribute("dob"));
System.out.println("age : " + name.getAttribute("age"));
System.out.println("validity : " + name.getAttribute("validity"));
//to get grouped node, the problem seems to be here
Node node3=nodeList3.item(temp2);
if(node3.hasChildNodes()){
Element grouped=(Element)node3;
if(node3.getNodeType()==Node.ELEMENT_NODE){
System.out.println("id:" + grouped.getAttribute("id"));
System.out.println("value1:" + grouped.getAttribute("value1"));
System.out.println("value2:" + grouped.getAttribute("value2"));
System.out.println("type:" + grouped.getAttribute("type"));
System.out.println("value7:" + grouped.getAttribute("value7"));
}
}
}
}
}
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}

Below is your modified code
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File fXmlFile = new File("D://test3.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nodeList0 = doc.getElementsByTagName("Service");
NodeList nodeList1 = doc.getElementsByTagName("File");
NodeList nodeList2 = doc.getElementsByTagName("name");
NodeList nodeList3 = doc.getElementsByTagName("grouped");
System.out.println("Root element :"
+ doc.getDocumentElement().getNodeName());
for (int temp0 = 0; temp0 < nodeList0.getLength(); temp0++) {
Node node0 = nodeList0.item(temp0);
System.out.println("\nElement type :" + node0.getNodeName());
Element Service = (Element) node0;
System.out.println("----" + temp0 + "-------");
if (node0.getNodeType() == Node.ELEMENT_NODE) {
System.out
.println("Name : " + Service.getAttribute("name"));
System.out.println("regrx : "
+ Service.getAttribute("regrx"));
System.out.println("reverex"
+ Service.getAttribute("reverseExtention"));
for (int temp = 0; temp < nodeList1.getLength(); temp++) {
Node node1 = nodeList1.item(temp);
System.out.println("------file" + temp + "--------");
System.out.println("\nElement type :"
+ node1.getNodeName());
Element File = (Element) node1;
// used for getting file level
if (node1.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("rootProfile:"
+ File.getAttribute("rootProfile"));
System.out.println("extension : "
+ File.getAttribute("extension"));
System.out.println("seperator : "
+ File.getAttribute("seperator"));
System.out.println("targetSeperator : "
+ File.getAttribute("targetSeperator"));
for (int temp2 = 0; temp2 < nodeList2.getLength(); temp2++) {
Node node2 = nodeList2.item(temp2);
Element name = (Element) node2;
if (node2.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("id:"
+ name.getAttribute("id"));
System.out.println("usn : "
+ name.getAttribute("usn"));
System.out.println("dob : "
+ name.getAttribute("dob"));
System.out.println("age : "
+ name.getAttribute("age"));
System.out.println("validity : "
+ name.getAttribute("validity"));
// to get grouped node, the problem seems to
// be here
// Node node3 = nodeList3.item(temp2);
NodeList grouped = node2.getChildNodes();
if (grouped != null
&& grouped.getLength() > 0) {
for (int ii = 0; ii < grouped
.getLength(); ii++) {
Node group = grouped.item(ii);
{
NodeList gropedNames = group
.getChildNodes();
if (gropedNames != null
&& gropedNames
.getLength() > 0) {
for (int jj = 0; jj < gropedNames
.getLength(); jj++) {
if (gropedNames
.item(jj) != null
&& gropedNames
.item(jj)
.getAttributes() != null) {
System.out
.println(gropedNames
.item(jj)
.getAttributes()
.getNamedItem(
"id"));
System.out
.println(gropedNames
.item(jj)
.getAttributes()
.getNamedItem(
"value1"));
System.out
.println(gropedNames
.item(jj)
.getAttributes()
.getNamedItem(
"value2"));
System.out
.println(gropedNames
.item(jj)
.getAttributes()
.getNamedItem(
"value7"));
}
}
}
}
}
}
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

If you need the nested name tags under the grouped, then ask the elements from the grouped tag and not from the document.
Document.getElementsByTagName() gives you back all tags by that name, calling getElementsByTagName() on an Element will give you back all the descendant elements of the Elemenent (e.g. child, grandchild etc.).
You can safely cast the grouped Node to Element and call getElementsByTagName() on it:
NodeList groupedNodeList = doc.getElementsByTagName("grouped");
for (int i = 0; i < groupedNodeList .getLength(); i++) {
Element groupedElement = (Element) groupedNodeList .item(i);
NodeList nameList = groupedElement.getElementsByTagName("name");
// Here you go, you have the list of name tags UNDER grouped
// Printing the id and value attributes of the name tag:
for (int j = 0; j < nameList.getLength(); j++) {
Element name = (Element) nameList.item(j);
System.out.println("Found <name>: id=" + name.getAttribute("id"));
System.out.println("\tvalue1=" + name.getAttribute("value1"));
System.out.println("\tvalue2=" + name.getAttribute("value2"));
System.out.println("\tvalue7=" + name.getAttribute("value7"));
}
}
Output is:
Found <name>: id=343
value1=TYPE0
value2=TYPE4
value7=1
Found <name>: id=564
value1=TYPE6
value2=TYPE7
value7=0

Related

Java DOM Parser reading xml files information - nodes attributes

I have got an xml file and try to read in some information and try to arrange them.
The data in the xml looks like:
<Class code="1-10" kind="category">
<Meta name="P17b-d" value="2"/>
<SuperClass code="1-10...1-10"/>
<SubClass code="1-100"/>
<Rubric kind="preferred">
<Label xml:lang="de" xml:space="default">Klinische Untersuchung</Label>
</Rubric>
</Class>
and my Java class looks like:
import java.io.File;
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 Importer {
public static void main(String[] args) {
try {
File inputFile = new File("ops2022.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Class");
for (int temp = 0; temp < 10; temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName() );
Element iElement = (Element) nNode;
if (nNode.getNodeType() == Node.ELEMENT_NODE && iElement.getAttribute("kind").equals("category") ) {
Element eElement = (Element) nNode;
System.out.println("code : "
+ eElement.getAttribute("code"));
System.out.println("Label : "
+ eElement
.getElementsByTagName("Label")
.item(0)
.getTextContent());
System.out.println("SuperClass : "
+ eElement
.getElementsByTagName("SuperClass")
//I don't know how to get the attribute code here
);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
But how do I get the attribute's information of the "SuperClass" Node? Idon't know why but java handles eElement.getAttributeNode("SuperClass") as a node, although it is an Element. So I can't use the getAttribute().
I added the code in your answer (#Hiran Chaudhuri) to get my needed information:
import java.io.File;
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 Importer {
public static void main(String[] args) {
try {
File inputFile = new File("ops2022.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Class");
for (int temp = 0; temp < 10; temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName() );
Element iElement = (Element) nNode;
if (nNode.getNodeType() == Node.ELEMENT_NODE && iElement.getAttribute("kind").equals("category") ) {
Element eElement = (Element) nNode;
System.out.println("code : "
+ eElement.getAttribute("code"));
System.out.println("Label : "
+ eElement
.getElementsByTagName("Label")
.item(0)
.getTextContent());
System.out.println("SuperClass : "
+ eElement
.getElementsByTagName("SuperClass")
Node n = eElement.getElementsByTagName("SuperClass").item(0);
if (n instanceof Attr) {
Attr a = (Attr)n;
System.out.println(a.getName());
System.out.println(a.getValue());
}
);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
And I get the following
----------------------------
Current Element :Class
Current Element :Class
Current Element :Class
code : 1-10
Label : Klinische Untersuchung
and if I add another else clause like
else {
Attr a = (Attr)n;
System.out.println(a.getValue());
}
java throws the following error:
java.lang.ClassCastException: class com.sun.org.apache.xerces.internal.dom.DeferredElementImpl cannot be cast to class org.w3c.dom.Attr (com.sun.org.apache.xerces.internal.dom.DeferredElementImpl and org.w3c.dom.Attr are in module java.xml of loader 'bootstrap')
at Importer.main(Importer.java:46)
.
With Element.getAttributeNode() you do receive a subclass/subinterface of Node called Attr. This Attr has getName() and getValue() methods that you should be interested in.
Using Element.getAttribute() will directly deliver the value of the corresponding attribute.
If you lost the chance to directly obtain the correct type, you can still recover like
Node n = ... // this is the attribute you are interested in
if (n instanceof Attr) {
Attr a = (Attr)n;
System.out.println(a.getName());
System.out.println(a.getValue());
}
So you are wondering how to access the SuperClass' code attribute. This code prints exactly the one value:
Document doc = dBuilder.parse(inputFile);
NodeList nList = doc.getElementsByTagName("Class"); // this list only contains Element nodes
for (int temp = 0; temp < nList.getLength(); temp++) {
Element nNode = (Element)nList.item(temp); // this is one 'class' element
NodeList nList2 = nNode.getElementsByTagName("SuperClass"); // this list only contains Element nodes
for (int temp2 = 0; temp2 < nList2.getLength(); temp2++) {
Element superclass = (Element)nList2.item(temp2);
String code = superclass.getAttribute("code");
System.out.println(code);
}
}
However this code does the same:
Document doc = dBuilder.parse(inputFile);
XPath xpath = XPathFactory.newInstance().newXPath();
String code = xpath.evaluate("/Class/SuperClass/#code", doc);
With XPath expressions you can navigate the DOM tree much more efficiently.
The following code did the job for me:
for (int i = 0; i < nList.getLength(); i++) {
//for (int i = 0; i < 20; i++) {
Node nNode = nList.item(i);
//System.out.println("\nCurrent Element :" + nNode.getNodeName() );
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String supString = "OPS-2022";
NodeList fieldNodes = eElement.getElementsByTagName("SuperClass");
for(int j = 0; j < fieldNodes.getLength(); j++) {
Node fieldNode = fieldNodes.item(j);
NamedNodeMap attributes = fieldNode.getAttributes();
Node attr = attributes.getNamedItem("code");
if(attr != null) {
supString =attr.getTextContent();
}
}
}
}
Thanks for your help!

Passing integer as string in java

I am parsing an xml file which has one table as below:
<table name="categoryAttributeTable">
<row>
<field name="CID">201</field>
<field name="name">page_title</field>
<field name="value">Spotlight</field>
</row>
<row>
<field name="CID">301</field>
<field name="name">page_title</field>
<field name="value">Oryx highlights</field>
</row>
<row>
<field name="CID">501</field>
<field name="name">page_title</field>
<field name="value">Little Taster</field>
</row>
</table>
I want to search value of CID 301 for which the ans should be Oryx highlights but i am getting Spotlight as ans which is the value of CID 201. Why this might be happening???
My java code is :
public static void main(String argv[]) {
try {
File fXmlFile = new File("/home/media.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("table");
System.out.println("----------------------------");
String titlevalue=null;
String cidvalue=null;
String lidvalue=null;
List a = new ArrayList();
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if(eElement.getAttribute("name").equalsIgnoreCase("categoryAttributeTable"))
{
NodeList nList1 = eElement.getElementsByTagName("row");
for (int temp1 = 0; temp1 < nList1.getLength(); temp1++) {
Node nNode1 = nList1.item(temp1);
if (nNode1.getNodeType() == Node.ELEMENT_NODE) {
Element eElement1 = (Element) nNode1;
NodeList nList2 = eElement1.getElementsByTagName("field");
for (int temp2 = 0; temp2 < nList2.getLength(); temp2++) {
Node nNode2 = nList2.item(temp2);
if (nNode2.getNodeType() == Node.ELEMENT_NODE) {
Element eElement2 = (Element) nNode2;
if(eElement2.getAttribute("name").equalsIgnoreCase("value"))
{
titlevalue=eElement2.getTextContent();
// System.out.println(" Title value :: "+titlevalue);
}
if(eElement2.getAttribute("name").equalsIgnoreCase("CID") && (eElement2.getTextContent().equals(String.valueOf(301))))
{
System.out.println(" Title value :: "+titlevalue);
}
}
}
}
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
In eElement2.getAttribute("name").equalsIgnoreCase() if i pass string then the output is coming as expected but if i pass integer as string then it is showing previous level's ans.
Please help me...
See this...
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ReadXMLFile {public static void main(String argv[]) {
try {
File fXmlFile = new File("src/test.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :"+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("table");
System.out.println("----------------------------");
String titlevalue=null;
String cidvalue=null;
String lidvalue=null;
List<String> valueList=new ArrayList<String>();
List<String> cidList=new ArrayList<String>();
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
if(eElement.getAttribute("name").equalsIgnoreCase("categoryAttributeTable"))
{
NodeList nList1 = eElement.getElementsByTagName("row");
for (int temp1 = 0; temp1 < nList1.getLength(); temp1++) {
Node nNode1 = nList1.item(temp1);
if (nNode1.getNodeType() == Node.ELEMENT_NODE) {
Element eElement1 = (Element) nNode1;
NodeList nList2 = eElement1.getElementsByTagName("field");
for (int temp2 = 0; temp2 < nList2.getLength(); temp2++) {
Node nNode2 = nList2.item(temp2);
if (nNode2.getNodeType() == Node.ELEMENT_NODE) {
Element eElement2 = (Element) nNode2;
String value1=null;
String value2=null;
if(eElement2.getAttribute("name").equalsIgnoreCase("value"))
{
valueList.add(eElement2.getTextContent());
// System.out.println(" Title value :: "+eElement2.getTextContent());
}
if(eElement2.getAttribute("name").equalsIgnoreCase("CID") && !(eElement2.getTextContent().equals("NULL")))
{
// System.out.println(" XXXXXXXXXXX Title value :: "+eElement2.getTextContent());
cidList.add(eElement2.getTextContent());
}
}
}
}
}
}
}
}
for(int i=0;i<valueList.size();i++)
{
System.out.println("value :: "+ valueList.get(i)+" corresponding cid :: "+ cidList.get(i));
//System.out.println("cid :: "+ cidList.get(i));
}
}
catch (Exception e) {
e.printStackTrace();
}
}}
I just want to point out where your mistake is. This is your original code.
if (nNode2.getNodeType() == Node.ELEMENT_NODE) {
Element eElement2 = (Element) nNode2;
if(eElement2.getAttribute("name").equalsIgnoreCase("value")){
titlevalue=eElement2.getTextContent();
}
if(eElement2.getAttribute("name").equalsIgnoreCase("CID") && (eElement2.getTextContent().equals(String.valueOf(301)))) {
System.out.println(" Title value :: "+titlevalue);
}
}
<row>
<field name="CID">201</field>
<field name="name">page_title</field>
<field name="value">Spotlight</field>
</row>
<row>
<field name="CID">301</field>
<field name="name">page_title</field>
<field name="value">Oryx highlights</field>
</row>
The order of the values of name attribute are CID, name and value. In the end of first loop of row tag, you will set titlevalue = Spotlight. Then in the beginning of second loop of row tag, you will skip the first if as the first field attribute is equal to CID. But the program will enter the second if because you define name=CID and the content=301, hence it displays titlevalue = Spotlight.
Try this.
Element eElement1 = (Element) nNode1;
NodeList nList2 = eElement1.getElementsByTagName("field");
for (int temp2 = 0; temp2 < nList2.getLength(); temp2++) {
Node nNode2 = nList2.item(temp2);
if (nNode2.getNodeType() == Node.ELEMENT_NODE) {
Element eElement2 = (Element) nNode2;
String nameattr = eElement2.getAttribute("name");
if (nameattr.equalsIgnoreCase("CID")) {
titlevalue = eElement2.getTextContent();
// If CID != 301, skip the whole loop.
if (!titlevalue.equalsIgnoreCase("301")) {
break;
}
}
else if (nameattr.equalsIgnoreCase("value")) {
System.out.println("value: " + eElement2.getTextContent());
}
}
}

Parsing XML from webpage

If I copy and paste the xml from this site into a xml file I can parse it with java
http://api.indeed.com/ads/apisearch?publisher=8397709210207872&q=java&l=austin%2C+tx&sort&radius&st&jt&start&limit&fromage&filter&latlong=1&chnl&userip=1.2.3.4&v=2
However, I want to parse it directly from a webpage if possible!
Here's my current code:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
public class XMLParser {
public void readXML(String parse) {
File xml = new File(parse);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xml);
// System.out.println("Root element :"
// + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("result");
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("job title : "
+
eElement.getElementsByTagName("jobtitle").item(0)
.getTextContent());;
System.out.println("Company: "
+
eElement.getElementsByTagName("company")
.item(0).getTextContent());
System.out.println("City : "
+
eElement.getElementsByTagName("city").item(0)
.getTextContent());
System.out.println("State : "
+
eElement.getElementsByTagName("state").item(0)
.getTextContent());
System.out.println("Country : "
+
eElement.getElementsByTagName("country").item(0)
.getTextContent());
System.out.println("Date posted : "
+
eElement.getElementsByTagName("date").item(0)
.getTextContent());
System.out.println("Job summary : "
+
eElement.getElementsByTagName("snippet").item(0)
.getTextContent());
System.out.println("Latitude : "
+
eElement.getElementsByTagName("latitude").item(0).getTextContent());
System.out.println("longitude : "
+
eElement.getElementsByTagName("longitude").item(0).getTextContent());
}
}
} catch (ParserConfigurationException | SAXException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new XMLParser().readXML("test.xml");
}
}
any help would be appreciated.
Give it the URI instead of the XML. It will download it for you.
Document doc = dBuilder.parse(uriString)
Please find the code snippet like this
String url = "http://api.indeed.com/ads/apisearch?publisher=8397709210207872&q=java&l=austin%2C+tx&sort&radius&st&jt&start&limit&fromage&filter&latlong=1&chnl&userip=1.2.3.4&v=2";
try
{
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
DocumentBuilder b = f.newDocumentBuilder();
Document doc = b.parse(url);
}
you need to have the element/nodes you want in a for loop. So it can scan through xml file, and find the right node you searching for.
reads the xml file as a string, and creates a xml structure
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(connection.getInputStream());
NodeList nodes = doc.getElementsByTagName("mode");
for (int i = 0; i < nodes.getLength(); i++)
Element element = (Element) nodes.item(i);
//Gets tag from XML and it´s content
NodeList nodeMode = element.getElementsByTagName("mode");
Element elemMode = (Element) nodeMode.item(0);
and after if you want to pick out a value and parse to an int or what you want you do like this:
int currentMode = Integer.parseInt(elemMode.getFirstChild().getTextContent());
That's how I parsed data directly from url http://www.nbp.pl/kursy/xml/+something
static class Kurs {
public float kurs_sprzedazy;
public float kurs_kupna;
}
private static DocumentBuilder dBuilder;
private static Kurs getData(String filename, String currency) throws Exception {
Document doc = dBuilder.parse("http://www.nbp.pl/kursy/xml/"+filename+".xml");
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("pozycja");
for(int i = 0; i < nList.getLength(); i++) {
Element nNode = (Element)nList.item(i);
if(nNode.getElementsByTagName("kod_waluty").item(0).getTextContent().equals(currency)) {
Kurs kurs = new Kurs();
String data = nNode.getElementsByTagName("kurs_sprzedazy").item(0).getTextContent();
data = data.replace(',', '.');
kurs.kurs_sprzedazy = Float.parseFloat(data);
data = nNode.getElementsByTagName("kurs_kupna").item(0).getTextContent();
data = data.replace(',', '.');
kurs.kurs_kupna = Float.parseFloat(data);
return kurs;
}
}
return null;
}

Why is this Java method not returning all XML Elements?

I'm working on reading DMX Values from an XML document. The method only returns one node from the element that I'm trying to pull from but there should be 512.
Here is the method:
public static void readXML(int cueNo){
try {
File fXmlFile = new File(MixWindow.Globals.fileLoc);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Cue");
System.out.println("-----------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = (Node) nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Cue Name : " + getTagValue("Cue_Name", eElement));
System.out.println("Cue Number : " + getTagValue("Cue_Number", eElement));
//System.out.println("Nick Name : " + getTagValue("nickname", eElement));
//System.out.println("Salary : " + getTagValue("salary", eElement));
}
}
NodeList nListII = doc.getElementsByTagName("DMX");
//nListII = doc.getElementsByTagName("DMX");
System.out.println("-----------------------");
int length = nListII.getLength();
System.out.println("DMX Length: " + length);
for (int tempII = 0; tempII < nListII.getLength(); tempII++) {
Node nNodeII = (Node) nListII.item(tempII);
if (nNodeII.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNodeII;
System.out.println("DMX Chnl: " + getTagValue("DMX_Chnl", eElement));
System.out.println("DMX Val: " + getTagValue("DMX_Val", eElement));
//System.out.println("Nick Name : " + getTagValue("nickname", eElement));
//System.out.println("Salary : " + getTagValue("salary", eElement));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
}
Here is a portion of the XML file:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ShowFile>
<Cue>
<Cue_Name>stuff and junk</Cue_Name>
<Cue_Number>1</Cue_Number></Cue>
<DMX>
<DMX_Chnl>1</DMX_Chnl>
<DMX_Val>0</DMX_Val>
<DMX_Chnl>2</DMX_Chnl>
<DMX_Val>0</DMX_Val>
<DMX_Chnl>3</DMX_Chnl>
<DMX_Val>0</DMX_Val>
<DMX_Chnl>4</DMX_Chnl>
<DMX_Val>0</DMX_Val>
......
<DMX_Chnl>512</DMX_Chnl>
<DMX_Val>0</DMX_Val>
System.out created this:
Cue Name : stuff and junk
Cue Number : 1
-----------------------
DMX Length: 1
DMX Chnl: 1
DMX Val : 0
What am I doing wrong?
shortened xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><ShowFile><Cue><Cue_Name>Stuff and Junk</Cue_Name><Cue_Number>1</Cue_Number></Cue><DMX><DMX_Chnl>1</DMX_Chnl><DMX_Val>0</DMX_Val><DMX_Cue>1</DMX_Cue><DMX_Chnl>2</DMX_Chnl><DMX_Val>0</DMX_Val><DMX_Cue>1</DMX_Cue><DMX_Chnl>3</DMX_Chnl><DMX_Val>0</DMX_Val><DMX_Cue>1</DMX_Cue><DMX_Chnl>4</DMX_Chnl></DMX></ShowFile>
added loop:
if (nNodeII.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNodeII;
NodeList childNodes = nNodeII.getChildNodes();
String result = new String();
for (int i = 0; i < childNodes.getLength(); i++) {
Node node = childNodes.item(i);
String dcName = node.getNodeName();
String dcVal = node.getNodeValue();
System.out.println("DMX stuff: " + dcName + " " + dcVal);
}
}
Java and the XML parser behave correctly.
But you expect the document to have a different structure than it actually does! So you are looking in the wrong place for nodes, and thus not finding nodes there.
There is only one DMX element. You want to enumerate the children, not the DMX elements.
(i.e. you want to have DMX_Chnl elements, and these are not each wrapped in a separate DMX node)

creating RDF triple and RDF store using jena from xml file

I use the following java program to extract information from an xml file.
import java.io.File;
import java.net.URL;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class ExtractInfo {
public static void main(String argv []) {
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
File file = new File("page.xml");
Document doc = docBuilder.parse(file);
// 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());
}
}
} catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line "
+ err.getLineNumber () + ", uri " + err.getSystemId());
System.out.println(" " + err.getMessage());
} catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
Could some one please help me in generating RDF triples from the extracted information and create a triple store using Jena containing all the triples. I am quite new to RDF, and Jena, So I do need your help guys ,
Thanks in advance.
Resource resource=OntModel.createResourc(NameSpace+"Doutorado_em_Engenharia_de_Sistemas_e_Computacao");
Property prop=OntModel.createProperty(http://www.owl-ontologies.com/OntologyBase.owl#program_Provided_By);
Resource obj=OntModel.createResource(NameSpace+"Universidade_X");
OntMode.add(resource,prop,obj);
Before applying it, you should first create an instance of OntModel for your ontology.
http://answers.semanticweb.com/questions/11084/add-triples-in-an-ontology-using-jena-api

Categories