I've followed almost all of the SO questions and answers, some make sense while others don't, i'm able to get some of my xml working some of the time. At this point I have a hobbled gob of nothing.
Below is my xml that i am trying work with
<GET_GUESS_CHART>
<sort_by_letter>
<letter_row>
<letter>A</letter>
<guess>16</guess>
<rank>3</rank>
</letter_row>
<letter_row>
<letter>B</letter>
<guess>5</guess>
<rank>1</rank>
</letter_row>
</sort_by_letter>
<sort_by_rank>
<letter_row>
<letter>A</letter>
<guess>16</guess>
<rank>1</rank>
</letter_row>
<letter_row>
<letter>E</letter>
<guess>15</guess>
<rank>2</rank>
</letter_row>
</sort_by_rank>
</GET_GUESS_CHART>
I want to loop through the document and loop through 'sort_by_letters' and 'sort_by_rank' and get values for each 'letter_row'.
Here is how i get the document:
URL url = new URL(Url[0]);
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Download the XML file
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
I'm able to actually get the document, but for the life of me can not figure how to work it to get what i need.
All you need to do is to walk the DOM tree...
import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ReadXML {
private static final String XML = "<?xml version=\"1.0\"?>\n"
+ "<GET_GUESS_CHART>"
+ " <sort_by_letter>"
+ " <letter_row>"
+ " <letter>A</letter>"
+ " <guess>16</guess>"
+ " <rank>3</rank>"
+ " </letter_row>"
+ " <letter_row>" +
+ " <letter>B</letter>"
+ " <guess>5</guess>"
+ " <rank>1</rank>"
+ " </letter_row>"
+ " </sort_by_letter>"
+ " <sort_by_rank>"
+ " <letter_row>"
+ " <letter>A</letter>"
+ " <guess>16</guess>"
+ " <rank>1</rank>"
+ " </letter_row>"
+ " <letter_row>"
+ " <letter>E</letter>"
+ " <guess>15</guess>"
+ " <rank>2</rank>"
+ " </letter_row>"
+ " </sort_by_rank>"
+ "</GET_GUESS_CHART>";
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ByteArrayInputStream(XML.getBytes()));
NodeList rootElement = doc.getChildNodes();
NodeList sortByNodes = rootElement.item(0).getChildNodes();
for (int k = 0; k < sortByNodes.getLength(); k++) {
Node sortBy = sortByNodes.item(k);
System.out.println("SORT BY: " + sortBy.getNodeName());
NodeList letterRows = sortBy.getChildNodes();
for (int j = 0; j < letterRows.getLength(); j++) {
Node letterRow = letterRows.item(j);
NodeList letterRowDetails = letterRow.getChildNodes();
if (letterRowDetails.getLength() > 0) {
String letter = null;
String guess = null;
String rank = null;
for (int i = 0; i < letterRowDetails.getLength(); i++) {
Node detail = letterRowDetails.item(i);
if (detail.getNodeName().equals("letter")) {
letter = detail.getTextContent();
} else if (detail.getNodeName().equals("guess")) {
guess = detail.getTextContent();
} else if (detail.getNodeName().equals("rank")) {
rank = detail.getTextContent();
}
}
System.out.println("Letter=" + letter + ", guess=" + guess + ", rank=" + rank);
}
}
}
}
}
(You'll probably build an object and add it to some result list instead of the System.out line...)
OUTPUT:
SORT BY: #text
SORT BY: sort_by_letter
Letter=A, guess=16, rank=3
Letter=B, guess=5, rank=1
SORT BY: #text
SORT BY: sort_by_rank
Letter=A, guess=16, rank=1
Letter=E, guess=15, rank=2
To answer the comment: if you wanted to JUST get the "sort_by_letter" XML elements, you can add an extra if clause here...
...
for (int k = 0; k < sortByNodes.getLength(); k++) {
Node sortBy = sortByNodes.item(k);
if(sortBy.getNodeName().equals("sort_by_letter")) {
System.out.println("SORT BY: " + sortBy.getNodeName());
...
Related
I am facing a issue where I am not able to get the value in my hashmap as per the key of the XML while I am getting the parent key
Code I am using:
public static void main(String[] args) throws IOException {
try {
String XML="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" +
"<sj0:Msg>\r\n" +
" xmlns:sj0=\"http://fakesite.org/\"\r\n" +
" xmlns:sj1=\"http://fakesite.org/ind\"\r\n" +
" <sj0:Hdr>\r\n" +
" <sj2:Option>CreateTxn</sj2:Option>\r\n" +
" <sj2:ID>172246</sj2:ID>\r\n" +
" <sj2:CountryCode>CR</sj2:CountryCode>\r\n" +
" </sj0:Hdr>\r\n" +
" <sj0:ReqDet>\r\n" +
" <sj0:MReq>\r\n" +
" <sj0:qCore>\r\n" +
" <sj1:Reference>12345678</sj1:Reference>\r\n" +
" <sj1:BrnCode>CLM</sj1:BrnCode>\r\n" +
" <sj1:Source>M1T722</sj1:Source>\r\n" +
" <sj1:TxnLegCount>2</sj1:TxnLegCount>\r\n" +
" </sj0:qCore>\r\n" +
" </sj0:MReq>\r\n" +
" <sj0:LReq>\r\n" +
" <sj0:RCore>\r\n" +
" <sj1:Amt>19.28</sj1:Amt>\r\n" +
" <sj1:Dt>2019-09-04</sj1:Dt>\r\n" +
" <sj1:Date>2019-06-27</sj1:Date>\r\n" +
" </sj0:RCore>\r\n" +
" </sj0:LReq>\r\n" +
" <sj0:LReq>\r\n" +
" <sj0:RCore>\r\n" +
" <sj1:Ind>DC</sj1:Ind>\r\n" +
" <sj1:Currency>US</sj1:Currency>\r\n" +
" <sj1:LAmt>20.28</sj1:LAmt>\r\n" +
" </sj0:RCore>\r\n" +
" </sj0:LReq>\r\n" +
" </sj0:ReqDet>\r\n" +
"</sj0:Msg>";
String XString = XML;
System.out.println(XML);
HashMap<String, String> values = new HashMap<String, String>();
Document xml = convertStringToDocument(XString);
Node user = xml.getFirstChild();
NodeList childs = user.getChildNodes();
Node child;
for (int i = 0; i < childs.getLength(); i++) {
child = childs.item(i);
System.out.println(child.getNodeName());
System.out.println(child.getNodeType());
System.out.println(child.getUserData("Source"));
System.out.println(child.getTextContent());
values.put(child.getNodeName(), child.getTextContent());
}
System.out.println("Source name");
System.out.println(values.toString());
System.out.println(values.get("Source"));
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xmlStr.getBytes("UTF-8"))));
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Output:
{sj0:ReqDet=
12345678
CLM
M1T722
2
19.28
2019-09-04
2019-06-27
DC
US
20.28
, #text= , sj0:Hdr= CreateTxn 172246 CR }
I need to add Source in haspmap key not ReqDet.
I am facing issue to traverse through the XML.
Any idea where I am going wrong and also please explain how I can get the value of other keys-value i.e. Ind key of RCore parent key.
I am fine with any other approach or library to do achieve this task if this library have issue
below line of code having "*" which means it will select all nodes/key-values from the XML
NodeList nodeList = doc.getElementsByTagName("*");
Below is the full code works for me:
public static void main(String[] args) throws IOException {
String XML="YOUR XML";
HashMap<String, String> values =convertStringToDocument(XML);
System.out.println("values = "+values.get("sj1:Source"));
}
public static HashMap<String, String> convertStringToDocument(String xmlStr) {
HashMap<String, String> values = new HashMap<String, String>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
EntityResolver resolver = new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) {
String empty = "";
ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
System.out.println("resolveEntity:" + publicId + "|" + systemId);
return new InputSource(bais);
}
};
builder.setEntityResolver(resolver);
Document doc = builder.parse(new InputSource(new ByteArrayInputStream(xmlStr.getBytes("UTF-8"))));
NodeList nodeList = doc.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
values.put(node.getNodeName(), node.getTextContent());
}
}
return values;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
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
I'm having some trouble parsing an XML file in Java. The file takes the form:
<root>
<thing>
<name>Thing1</name>
<property>
<name>Property1</name>
</property>
...
</thing>
...
</root>
Ultimately, I would like to convert this file into a list of Thing objects, which will have a String name (Thing1) and a list of Property objects, which will each also have a name (Property1).
I've been trying to use xpaths to get this data out, but when I try to get just the name for 'thing', it gives me all of the names that appear in 'thing', including those of the 'property's. My code is:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(filename);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression thingExpr = xpath.compile("//thing");
NodeList things = (NodeList)thingExpr.evaluate(dom, XPathConstants.NODESET);
for(int count = 0; count < things.getLength(); count++)
{
Element thing = (Element)things.item(count);
XPathExpression nameExpr = xpath.compile(".//name/text()");
NodeList name = (NodeList) nameExpr.evaluate(thing, XPathConstants.NODESET);
for(int i = 0; i < name.getLength(); i++)
{
System.out.println(name.item(i).getNodeValue());
}
}
Can anyone help? Thanks in advance!
You could try something like...
public class TestXPath {
public static void main(String[] args) {
String xml =
"<root>\n"
+ " <thing>\n"
+ " <name>Thing1</name>\n"
+ " <property>\n"
+ " <name>Property1</name>\n"
+ " </property>\n"
+ " <property>\n"
+ " <name>Property2</name>\n"
+ " </property>\n"
+ " <property>\n"
+ " <name>Property3</name>\n"
+ " </property>\n"
+ " <property>\n"
+ " <name>Property4</name>\n"
+ " </property>\n"
+ " <property>\n"
+ " <name>Property5</name>\n"
+ " </property>\n"
+ " </thing>/n"
+ " <NoAThin>\n"
+ " <name>Thing2</name>\n"
+ " <property>\n"
+ " <name>Property1</name>\n"
+ " </property>\n"
+ " <property>\n"
+ " <name>Property2</name>\n"
+ " </property>\n"
+ " <property>\n"
+ " <name>Property3</name>\n"
+ " </property>\n"
+ " <property>\n"
+ " <name>Property4</name>\n"
+ " </property>\n"
+ " <property>\n"
+ " <name>Property5</name>\n"
+ " </property>\n"
+ " </NoAThin>/n"
+ "</root>";
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
Document dom = db.parse(bais);
XPath xpath = XPathFactory.newInstance().newXPath();
// Find the "thing" node...
XPathExpression thingExpr = xpath.compile("/root/thing");
NodeList things = (NodeList) thingExpr.evaluate(dom, XPathConstants.NODESET);
System.out.println("Found " + things.getLength() + " thing nodes...");
// Find the property nodes of thing
XPathExpression expr = xpath.compile("property");
NodeList nodes = (NodeList) expr.evaluate(things.item(0), XPathConstants.NODESET);
System.out.println("Found " + nodes.getLength() + " thing/property nodes...");
// Find all the property "name" nodes under thing
expr = xpath.compile("property/name");
nodes = (NodeList) expr.evaluate(things.item(0), XPathConstants.NODESET);
System.out.println("Found " + nodes.getLength() + " name nodes...");
System.out.println("Property value = " + nodes.item(0).getTextContent());
// Find all nodes that have property nodes
XPathExpression exprAll = xpath.compile("/root/*/property");
NodeList nodesAll = (NodeList) exprAll.evaluate(dom, XPathConstants.NODESET);
System.out.println("Found " + nodesAll.getLength() + " property nodes...");
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
Which will give you an output of something like
Found 1 thing nodes...
Found 5 thing/property nodes...
Found 5 name nodes...
Property value = Property1
Found 10 property nodes...
How about "//thing/name/text()" ?
The double slashes you have now before name mean "anywhere in the tree, not necessarily direct child nodes".
Use these XPath expressions:
//thing[name='Thing1']
this selects any thing element in the XML document, that has a name child whose string value is "Thing1".
also use:
//property[name='Property1']
this selects any property element in the XML document, that has a name child whose string value is "Property1".
Update:
To get all text nodes, each containing a string value of a thing element, just do:
//thing/text()
In XPath 2.0 one can get a sequence of the strings themselves, using:
//thing/string(.)
This isn't possible with a single XPath expression, but one can get the string value of a particular (the n-th)thing element like this:
string((//thing)[$n])
where $n must be substituted with a specific number from 1 to count(//thing) .
So, in your prograaming language, you can first determine cnt by evaluating this XPath expression:
count(//thing)
And then in a loop for $n from 1 to cnt dynamically produce the xpath expression and evaluate it:
string((//thing)[$n])
Exactly the same goes for obtaining all the values for property elements.
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
I have been working on this problem for quite some time and can't figure it out. There is a given "xml" file that needs to be parsed and displayed on the screen:
<office>
<name>joe</name>
<surname>smith</surname>
<name>bob</name>
<surname>black</surname>
.....
</office>
I've found some great samples of codes on line but they don't seem to work with an xml file that's not set up correctly as this one, so if I'd add a tag I can get my code to work, but the problem is I can't make any changes to the "xml" file.
It is someone else's code I found here that's been modified.
Here is my code with mods:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class ReadAndPrintXMLFile{
public static void main (String argv []) throws ParserConfigurationException, SAXException, IOException{
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("office.xml"));
// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " +
doc.getDocumentElement().getNodeName() + "\n");
//counts how many times <name> is found in the file
//then the number is used in the for loop below
NodeList listOfTerms = doc.getElementsByTagName("name");
int totalTerms = listOfTerms.getLength();
System.out.println("Total no of terms : " + totalTerms + "\n");
for(int s= 0; s<listOfTerms.getLength() ; s++){
Node firstTermNode = listOfTerms.item(s);
if(firstTermNode.getNodeType() == Node.ELEMENT_NODE){
Element firstTermElement = (Element)firstTermNode;
//-------
NodeList firstWordList = firstTermElement.getElementsByTagName("name");
Element firstWordElement = (Element)firstWordList.item(0);
NodeList textWordList = firstWordElement.getChildNodes();
System.out.println("Name : " +
((Node)textWordList.item(0)).getNodeValue().trim());
//-------
NodeList defList = firstTermElement.getElementsByTagName("surname");
Element defElement = (Element)defList.item(0);
NodeList textDefList = defElement.getChildNodes();
System.out.println("Surname : " +
((Node)textDefList.item(0)).getNodeValue().trim());
}//end of if clause
}//end of for loop with s var
}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 ();
}
//System.exit (0);
}//end of main
}
The error message I get is this:
java.lang.NullPointerException
at Data.main(Data.java:45) //maybe a different line in the code for you.
If I use the root of the document for counter it prints the result once, for some reason getChildNodes() is not working correctly.
I notice that you do a .getElementsByTagName("name") twice. Are you expecting <name> tags within <name> ? If not then that is most likely the cause of your error, since the second time, it would return an empty list and will cause a NullPointerException when you try to reference firstWordElement
You can't obtain the 'surname' from 'name' list which is what you are doing in the for loop. Get them in separate steps, so to fetch the 'name' elements:
NodeList listOfTerms = doc.getElementsByTagName("name");
int totalTerms = listOfTerms.getLength();
System.out.println("Total no of terms : " + totalTerms + "\n");
for(int s= 0; s<listOfTerms.getLength() ; s++){
Node firstTermNode = listOfTerms.item(s);
if(firstTermNode.getNodeType() == Node.ELEMENT_NODE){
Element firstTermElement = (Element)firstTermNode;
System.out.println(firstTermElement.getTextContent());
}//end of if clause
}//end of for loop with s var
and then to fetch the surname, just vary the tagname
listOfTerms = doc.getElementsByTagName("surname");
totalTerms = listOfTerms.getLength();
System.out.println("Total no of terms : " + totalTerms + "\n");
for(int s= 0; s<listOfTerms.getLength() ; s++){
Node firstTermNode = listOfTerms.item(s);
if(firstTermNode.getNodeType() == Node.ELEMENT_NODE){
Element firstTermElement = (Element)firstTermNode;
System.out.println(firstTermElement.getTextContent());
}//end of if clause
}//end of for loop with s var
Hope that helps.