I am trying parse an xml file by using below java code. The problem is while it is reading data from inner I can retrive data data from every where but if there are multi items under one package which means, while it does not retrive all child under parent would you please help?
import java.io.File;
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 ReadAndPrintXMLFile{
public static void ReadXmlandParce(String filename){
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File(filename));
// normalize text representation
doc.getDocumentElement ().normalize ();
System.out.println ("Root element of the doc is " +
doc.getDocumentElement().getNodeName());
NodeList Messagend = doc.getElementsByTagName("IMessage");
for(int s=0; s<Messagend.getLength() ; s++){
Node MessageItemNode = Messagend.item(s);
if(MessageItemNode.getNodeType() == Node.ELEMENT_NODE){
Element MessageElement = (Element)MessageItemNode;
//-------
NodeList MessageNamend = MessageElement.getElementsByTagName("IMessageName");
Element MessageNameElement = (Element)MessageNamend.item(0);
NodeList textMessageName = MessageNameElement.getChildNodes();
System.out.println("MessageName : " +
((Node)textMessageName.item(0)).getNodeValue().trim());
//-------
NodeList MessageDatend = MessageElement.getElementsByTagName("IMessageDate");
Element MessageDateElement = (Element)MessageDatend.item(0);
NodeList textMessageDate = MessageDateElement.getChildNodes();
System.out.println("MessageDate : " +
((Node)textMessageDate.item(0)).getNodeValue().trim());
//----
NodeList ServiceOrderednd = MessageElement.getElementsByTagName("IServiceOrderedType");
Element ServiceOrderedElement = (Element)ServiceOrderednd.item(0);
NodeList textServiceOrdered = ServiceOrderedElement.getChildNodes();
System.out.println("ServiceOrdered : " +
((Node)textServiceOrdered.item(0)).getNodeValue().trim());
//------
NodeList ServiceTypend = MessageElement.getElementsByTagName("IServiceType");
Element ServiceTypeElement = (Element)ServiceTypend.item(0);
NodeList textServiceType = ServiceTypeElement.getChildNodes();
System.out.println("ServiceType : " +
((Node)textServiceType.item(0)).getNodeValue().trim());
//------
NodeList SpecialInstructionsnd = MessageElement.getElementsByTagName("Instructions");
Element SpecialInstructionsElement = (Element)SpecialInstructionsnd.item(0);
NodeList textSpecialInstructions = SpecialInstructionsElement.getChildNodes();
System.out.println("SpecialInstructions : " +
((Node)textSpecialInstructions.item(0)).getNodeValue().trim());
//------
NodeList CompanyNamend = MessageElement.getElementsByTagName("CompanyName");
Element CompanyNameElement = (Element)CompanyNamend.item(0);
NodeList textCompanyName = CompanyNameElement.getChildNodes();
System.out.println("CompanyName : " +
((Node)textCompanyName.item(0)).getNodeValue().trim());
//------
}//end of if clause
}//end of for loop with s var
///////////////////////////////////
NodeList Consigneend = doc.getElementsByTagName("UConsignee");
for(int j=0; j<Consigneend.getLength() ; j++){
Node ConsigneeItemNode = Consigneend.item(j);
if(ConsigneeItemNode.getNodeType() == Node.ELEMENT_NODE){
Element ConsigneeElement = (Element)ConsigneeItemNode;
//-------
NodeList CompanyCodend = ConsigneeElement.getElementsByTagName("UCompanyCode");
Element CompanyCodeElement = (Element)CompanyCodend.item(0);
NodeList textCompanyCode = CompanyCodeElement.getChildNodes();
try{
System.out.println("UCompanyCode : " +((Node)textCompanyCode.item(0)).getNodeValue().trim());
}
catch (NullPointerException err ) {
System.out.println ("UCompanyCode : empty");
}
//-------
NodeList CompanyNamend = ConsigneeElement.getElementsByTagName("UCompanyName");
Element CompanyNameElement = (Element)CompanyNamend.item(0);
NodeList textCompanyName = CompanyNameElement.getChildNodes();
System.out.println("CompanyName : " +
((Node)textCompanyName.item(0)).getNodeValue().trim());
//----
NodeList TaxNond = ConsigneeElement.getElementsByTagName("UTaxNo");
Element TaxNoElement = (Element)TaxNond.item(0);
NodeList textTaxNo= TaxNoElement.getChildNodes();
System.out.println("TaxNo : " +
((Node)textTaxNo.item(0)).getNodeValue().trim());
//------
NodeList Street1nd = ConsigneeElement.getElementsByTagName("Street1");
Element Street1Element = (Element)Street1nd.item(0);
NodeList textStreet1 = Street1Element.getChildNodes();
try{
System.out.println("Street1 : " +
((Node)textStreet1.item(0)).getNodeValue().trim());
}
catch (NullPointerException err ) {
System.out.println ("Street1 : empty");
}
//----
NodeList Street2nd = ConsigneeElement.getElementsByTagName("Street2");
Element Street2Element = (Element)Street2nd.item(0);
NodeList textStreet2 = Street2Element.getChildNodes();
try{
System.out.println("Street2 : " +
((Node)textStreet2.item(0)).getNodeValue().trim());
}
catch (NullPointerException err ) {
System.out.println ("Street2 : empty");
}
//----
NodeList PostalCodend = ConsigneeElement.getElementsByTagName("PostalCode");
Element PostalCodeElement = (Element)PostalCodend.item(0);
NodeList textPostalCode = PostalCodeElement.getChildNodes();
try{
System.out.println("PostalCode : " +
((Node)textPostalCode.item(0)).getNodeValue().trim());
}
catch (NullPointerException err ) {
System.out.println ("PostalCode : empty");
}
//----
NodeList CityNamend = ConsigneeElement.getElementsByTagName("CityName");
Element CityNameElement = (Element)CityNamend.item(0);
NodeList textCityName = CityNameElement.getChildNodes();
try{
System.out.println("CityName : " +
((Node)textCityName.item(0)).getNodeValue().trim());
}
catch (NullPointerException err ) {
System.out.println ("CityName : empty");
}
//----
NodeList Countrynd = ConsigneeElement.getElementsByTagName("Country");
Element CountryElement = (Element)Countrynd.item(0);
NodeList textCountry = CountryElement.getChildNodes();
try{
System.out.println("Country : " +
((Node)textCountry.item(0)).getNodeValue().trim());
}
catch (NullPointerException err ) {
System.out.println ("Country : Bos");
}
//----
NodeList TaxRegNond = ConsigneeElement.getElementsByTagName("TaxRegNo");
Element TaxRegNoElement = (Element)TaxRegNond.item(0);
NodeList textTaxRegNo = TaxRegNoElement.getChildNodes();
try{
System.out.println("TaxRegNo : " +
((Node)textTaxRegNo.item(0)).getNodeValue().trim());
}
catch (NullPointerException err ) {
System.out.println ("TaxRegNo : empty");
}
//----
System.out.println ("+++++++++++++++++++++++++++");
System.out.println ("Begin of Package");
System.out.println ("+++++++++++++++++++++++++++");
NodeList Packagend = doc.getElementsByTagName("CPackage");
for(int k=0; k<Packagend.getLength() ; k++){
Node PackageItemNode = Packagend.item(k);
if(PackageItemNode.getNodeType() == Node.ELEMENT_NODE){
Element PackageElement = (Element)PackageItemNode;
//-------
NodeList PackageTypend = PackageElement.getElementsByTagName("CPackageType");
Element PackageTypeElement = (Element)PackageTypend.item(0);
NodeList textPackageType = PackageTypeElement.getChildNodes();
try{
System.out.println("PackageType : " +
((Node)textPackageType.item(0)).getNodeValue().trim());
}
catch (NullPointerException err ) {
System.out.println ("PackageType : empty");
}
//-------
NodeList GrossWeightnd = PackageElement.getElementsByTagName("CGrossWeight");
Element GrossWeightElement = (Element)GrossWeightnd.item(0);
NodeList textGrossWeight = GrossWeightElement.getChildNodes();
try{
System.out.println("GrossWeight : " +
((Node)textGrossWeight.item(0)).getNodeValue().trim());
}
catch (NullPointerException err ) {
System.out.println ("GrossWeight : empty");
}
//-------
NodeList Barcodend = PackageElement.getElementsByTagName("CBarcode");
Element BarcodeElement = (Element)Barcodend.item(0);
NodeList textBarcode = BarcodeElement.getChildNodes();
try{
System.out.println("Barcode : " +
((Node)textBarcode.item(0)).getNodeValue().trim());
}
catch (NullPointerException err ) {
System.out.println ("Barcode : empty");
}
//-------
System.out.println ("+++++++++++++++++++++++++++");
System.out.println ("Begin of Item");
System.out.println ("+++++++++++++++++++++++++++");
NodeList Itemnd = doc.getElementsByTagName("Item");
for(int p=0; p<Itemnd.getLength() ; p++){
Node ItemNode = Itemnd.item(p);
if(ItemNode.getNodeType() == Node.ELEMENT_NODE){
Element ItemElement = (Element)ItemNode;
NodeList ItemCodend = ItemElement.getElementsByTagName("ItemCode");
Element ItemCodeElement = (Element)ItemCodend.item(0);
NodeList textItemCode = ItemCodeElement.getChildNodes();
try{
System.out.println("ItemCode : " +
((Node)textItemCode.item(0)).getNodeValue().trim());
}
catch (NullPointerException err ) {
System.out.println ("ItemCode : empty");
}
//-------
NodeList Quantitynd = ItemElement.getElementsByTagName("ItemQuantity");
Element QuantityElement = (Element)Quantitynd.item(0);
NodeList textQuantity = QuantityElement.getChildNodes();
try{
System.out.println("Quantity : " +
((Node)textQuantity.item(0)).getNodeValue().trim());
}
catch (NullPointerException err ) {
System.out.println ("Quantity : empty");
}
//-------
}
}
}
}
}//end of if clause
}
///////////////////////////////////
}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);
}
}
Please find xml as below
<IMessage>
<IMessageName>IM1234</IMessageName>
<IMessageDate>20140328</IMessageDate>
<IServiceOrderedType>Normal</IServiceOrderedType>
<IServiceType>AIR</IServiceType>
<Instructions>OP123456</Instructions>
<CompanyName>Test</CompanyName>
<UConsignee>
<UCompanyCode></UCompanyCode>
<UTaxNo>T1231132123</UTaxNo>
<Street1>test132132</Street1>
<Street2>Streeet1</Street2>
<PostalCode>121212</PostalCode>
<CityName>London</CityName>
<Country>UK</Country>
<TaxRegNo>121313</TaxRegNo>
<CPackage>
<CPackageType>BIG</CPackageType>
<CGrossWeight>12</CGrossWeight>
<CBarcode>54353454353</CBarcode>
<Item>
<ItemCode>IT122111</ItemCode>
<ItemQuantity>50</ItemQuantity>
</Item>
<Item>
<ItemCode>IT122851</ItemCode>
<ItemQuantity>10</ItemQuantity>
</Item>
<Item>
<ItemCode>IT122151</ItemCode>
<ItemQuantity>18</ItemQuantity>
</Item>
</CPackage>
<CPackage>
<CPackageType>MEDIUM</CPackageType>
<CGrossWeight>14</CGrossWeight>
<CBarcode>54353454354</CBarcode>
<Item>
<ItemCode>IT18581</ItemCode>
<ItemQuantity>100</ItemQuantity>
</Item>
<Item>
<ItemCode>IT98561</ItemCode>
<ItemQuantity>60</ItemQuantity>
</Item>
<Item>
<ItemCode>IT68961</ItemCode>
<ItemQuantity>12</ItemQuantity>
</Item>
</CPackage>
</UConsignee>
</IMessage>
I have found answer that should be continue to iteration by nested NodeList methood as below code
NodeList PackageRootNodeList = Messagend .getElementsByTagName("CPackage");
for(int n=0; n<PackageRootNodeList .getLength() ; n++){
Node PackageNode = PackageRootNodeList .item(s);
Element PackageRootElement = (Element)PackageNode ;
//-------
NodeList PackageBarcodeNodeList = PackageRootElement .getElementsByTagName("CBarcode");
Element PackageBarcodeElement = (Element)PackageBarcodeNodeList .item(0);
NodeList textCBarcode = PackageBarcodeElement .getChildNodes();
System.out.println("CBarcode: " +
((Node)textCBarcode.item(0)).getNodeValue().trim());
/////
///// You will continue as the same methood in order to make deep iteration
/////
}
Related
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 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)
I have the xml file as follows,
<CHPkt xmlns="Smartscript/EmarSchema">
<CHInfo>
<StoreId>1800</StoreId>
<CHId>DB439A79-3D6F-4D25-BE0A-C4692978C072</CHId>
<CHName>Test</CHName>
<Address>
<Address1>Test Address</Address1>
</Address>
<DrugRounds>
<RoundTime>09:00</RoundTime>
<RoundTime>13:00</RoundTime>
<RoundTime>17:00</RoundTime>
</DrugRounds>
</CHInfo>
</CHPkt>
How to get the values of the tags which has the same name, my code is as follows,
public class ReadXml {
public static void main(String[] args){
try{
File xmlFile = new File("/home/jayakumar/Desktop/SmartScript.XML");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlFile);
NodeList nodeList1 = document.getElementsByTagName("CHInfo");
System.out.println("######################################");
for(int i =0;i<nodeList1.getLength();i++){
org.w3c.dom.Node node = nodeList1.item(i);
if(node.getNodeType()== org.w3c.dom.Node.ELEMENT_NODE){
Element element = (Element) node;
System.out.println("StoreId : " + getTagValue("StoreId", element));
System.out.println("CHId : " + getTagValue("CHId", element));
System.out.println("CHName : " + getTagValue("CHName", element));
System.out.println("Address : " + getTagValue("Address1", element));
}
NodeList nodeList2 = document.getElementsByTagName("DrugRounds");
System.out.println("-------------->"+"DrugRounds");
for(int j =0;j<nodeList2.getLength();j++){
org.w3c.dom.Node subNode = nodeList2 .item(j);
Element e = (Element) subNode;
System.out.println("RoundTime : "+getTagValue("RoundTime", e));
System.out.println("RoundTime : "+getTagValue("RoundTime", e));
System.out.println("RoundTime : "+getTagValue("RoundTime", e));
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static String getTagValue(String sTag, Element element) {
NodeList nlList = element.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
}
I wasn't able to extract the values of second and third Roudtimes.How to parse the tags with same name
Thanks
Why not just check if it has any child nodes then get the value from it
for (int j = 0; j < nodeList2.getLength(); j++) {
org.w3c.dom.Node subNode = nodeList2.item(j);
NodeList childNodes = subNode.getChildNodes();
for(int iDx = 0; iDx < childNodes.getLength(); iDx++){
if(childNodes.item(iDx) instanceof Element){
Element e = (Element) childNodes.item(iDx);
System.out.println("RoundTime : "+ e.getFirstChild().getNodeValue());
}
}
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 a simple XML file
<requirements>
<requirement>
<name> SwitchON</name>
<id>1</id>
<text>The Light shall turn on when the Switch is on.</text>
</requirement>
<requirement>
<name>SwitchOFF</name>
<id>2</id>
<text>The Light shall turn off when the Switch is off.</text>
</requirement>
<requirement>
<name>Lightbulb</name>
<id>3</id>
<text>The Light bulb shall be connected </text>
</requirement>
<requirement>
<name>Power</name>
<id>4</id>
<text>The Light shall have the power supply</text>
</requirement>
</requirements>
I am trying to show the information in this file in a table model.
I have a method (readFromXMl) that reads the XML file and returns a table model.
public static RequirementTable readFromXMl(String fileName) {
RequirementTable T = new RequirementTable();
Requirement R = new Requirement();
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File(fileName));
doc.getDocumentElement().normalize();
NodeList listOfRequirements = doc.getElementsByTagName("requirement");
int test = listOfRequirements.getLength();
System.out.println("Total no of people : " + test);
for (int i = 0; i < listOfRequirements.getLength(); i++) {
Node RequirementNode = listOfRequirements.item(i);
if (RequirementNode.getNodeType() == Node.ELEMENT_NODE) {
Element RequirementElement = (Element) RequirementNode;
NodeList IdList = RequirementElement.getElementsByTagName("id");
Element IdElement = (Element) IdList.item(0);
NodeList textIdList = IdElement.getChildNodes();
R.setId(Integer.parseInt(textIdList.item(0).getNodeValue()));
NodeList DescriptionList = RequirementElement.getElementsByTagName("text");
Element DescriptionElement = (Element) DescriptionList.item(0);
NodeList textDescriptionList = DescriptionElement.getChildNodes();
R.setText(textDescriptionList.item(0).toString());
NodeList NameList = RequirementElement.getElementsByTagName("name");
Element NameElement = (Element) NameList;
NodeList textNameList = NameElement.getChildNodes();
if (textNameList.item(0).toString().equals("SwitchON")) {
T.addRequirement((SwitchOnReq)R);
} else if (textNameList.item(0).toString().equals("SwitchOFF")) {
T.addRequirement((SwitchOFFReq)R);
} else if (textNameList.item(0).toString().equals("LightBulb")) {
T.addRequirement((BulbRequirement)R);
} else if (textNameList.item(0).toString().equals("Power")) {
T.addRequirement((PowerRequirement)R);
}
}
}
} 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();
}
return T;
}
However in this line I am getting an error which says the the pointer is null
Element IdElement = (Element) IdList.item(0); IdElement is null!!
Instead of all the looping and other xml ugliness, let me suggest a little helper method:
private static String getNodeValue(Node n, String path)
throws XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
return (String) xpath.evaluate(path, n, XPathConstants.STRING);
}
Use like this:
for (int i = 0; i < listOfRequirements.getLength(); i++) {
Node RequirementNode = listOfRequirements.item(i);
System.out.println("name:" + getNodeValue(RequirementNode, "name"));
System.out.println("id:" + getNodeValue(RequirementNode, "id"));
System.out.println("text:" + getNodeValue(RequirementNode, "text"));
...
to get all the values and set your requirements.