reading from XMl file in java - java

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.

Related

How to modify the manually added tag value in html

class HtmlTagmodifier {
public String htmlFileWriter(String cfile, String Listname, String Nodename, String nodevalue) {
try {
File fhtmlFile = new File(cfile);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fhtmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName(Listname);
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
eElement.getElementsByTagName(Nodename).item(0).setTextContent(nodevalue);
}
}
Source source = new DOMSource(doc);
Result htmlresult = new StreamResult(fhtmlFile);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, htmlresult);
result2 = "Success";
} catch (Exception e) {
e.printStackTrace();
log.error("Error in html file writing " + e.toString());
JOptionPane.showMessageDialog(null, "Error in html file writing " + e.toString());
result2 = "Failed";
}
return result2;
}
public static void main(String[] args) {
HtmlTagmodifier.htmlfilewriter("test.html", "details", "customername", "customernamexxxxxx");
}
}
Output:
when i use this method to modify the tag values of html,tag name is changed successfully but meta data tag is added again in the html
please give me suggestion.

java parsing xml and retriving child data from complex xml

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
/////
}

How to parse xml in android-java?

In my application, I have an XML file and I want to parse the XML file and extract data from the XML tags. Here is my XML file.
<array>
<recipe>
<name> Crispy Fried Chicken </name>
<description> Deliciously Crispy Fried Chicken</description>
<prepTime>1.5 hours </prepTime>
<instructions>instruction steps</instructions>
<ingredients>
<item>
<itemName>Chicken Parts</itemName>
<itemAmount>2 lbs</itemAmount>
</item>
<item>
<itemName>Salt & Peppers</itemName>
<itemAmount>As teste</itemAmount>
</item>
</ingredients>
</recipe>
<recipe>
<name> Bourben Chicken </name>
<description> A good recipe! A tad on the hot side!</description>
<prepTime>1 hours </prepTime>
<instructions>instruction steps</instructions>
<ingredients>
<item>
<itemName>Boneless Chicken</itemName>
<itemAmount>2.5 lbs</itemAmount>
</item>
<item>
<itemName>Olive Oil</itemName>
<itemAmount>1 -2 tablespoon</itemAmount>
</item>
<item>
<itemName>Olive Oil</itemName>
<itemAmount>1 -2 tablespoon</itemAmount>
</item>
</ingredients>
</recipe>
</array>
I have used DOM parser to parse the above xml file and I have extracted data from <name>, <description>, <prepTime> and <instructions> tags BUT I don't know how to extract data from <ingredients> TAG. You can see my code that I have developed for DOM parser. Here is my DOM parser
public class DOMParser
{
// parse Plist and fill in arraylist
public ArrayList<DataModel> parsePlist(String xml)
{
final ArrayList<DataModel> dataModels = new ArrayList<DataModel>();
//Get the xml string from assets XML file
final Document doc = convertStringIntoXML(xml);
// final NodeList nodes_array = doc.getElementsByTagName("array");
//Iterating through the nodes and extracting the data.
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
if (node instanceof Element)
{
DataModel model = new DataModel();
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++)
{
Node cNode = childNodes.item(j);
if (cNode instanceof Element)
{
String content = cNode.getLastChild().getTextContent().trim();
if(cNode.getNodeName().equalsIgnoreCase("name"))
model.setName(content);
else if(cNode.getNodeName().equalsIgnoreCase("description"))
model.setDescription(content);
else if(cNode.getNodeName().equalsIgnoreCase("prepTime"))
model.setPrepTime(content);
else if(cNode.getNodeName().equalsIgnoreCase("instructions"))
model.setInstructions(content);
}
}
dataModels.add(model);
}
}
return dataModels;
}
// Create xml document object from XML String
private Document convertStringIntoXML(String xml)
{
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
}
catch (ParserConfigurationException e)
{
System.out.println("XML parse error: " + e.getMessage());
return null;
}
catch (SAXException e)
{
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
}
catch (IOException e)
{
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
}
You need to iterate ingredients child nodes like you do it for recipe tag.
But the more easy way is to use XPath.
you can change your code as below.
public ArrayList<DataModel> parsePlist(String xml)
{
final ArrayList<DataModel> dataModels = new ArrayList<DataModel>();
//Get the xml string from assets XML file
final Document doc = convertStringIntoXML(xml);
//final NodeList nodes_array = doc.getElementsByTagName("array");
//Iterating through the nodes and extracting the data.
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
if (node instanceof Element)
{
DataModel model = new DataModel();
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++)
{
Node cNode = childNodes.item(j);
if (cNode instanceof Element)
{
String content = cNode.getLastChild().getTextContent().trim();
if(cNode.getNodeName().equalsIgnoreCase("name"))
model.setName(content);
else if(cNode.getNodeName().equalsIgnoreCase("description"))
model.setDescription(content);
else if(cNode.getNodeName().equalsIgnoreCase("prepTime"))
model.setPrepTime(content);
else if(cNode.getNodeName().equalsIgnoreCase("instructions"))
model.setInstructions(content);
else if(cNode.getNodeName().equalsIgnoreCase("ingredients"))
{
Element ingredEle = (Element)cNode;
NodeList ingredList = ingredEle
.getElementsByTagName("ingredients");
for (int i = 0; i < ingredList.getLength(); i++)
{
Element item = (Element)ingredList.item(i);
if(item.hasChildNodes())
{
NodeList itemList = item.getElementsByTagName("item");
for (int j = 0; j < itemList.getLength(); j++)
{
Element itemEle = (Element)itemList.item(j);
if (getNodeValue(itemEle, "itemName") != null)
{
String name = getNodeValue(itemEle, "itemName");
//set name here
}
if (getNodeValue(itemEle, "itemAmount") != null)
{
String amount = getNodeValue(itemEle,"itemAmount");
//set amount here
}
}
}
}
}
}
dataModels.add(model);
}
}
return dataModels;
}
private String getNodeValue(Element element, String elementTemplateLoc) {
NodeList nodes = element.getElementsByTagName(elementTemplateLoc);
return getTextNodeValue(nodes.item(0));
}
Hope this will work for you

Java:XML Parsing

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

How to read alternative tags in xml using java?

I have xml file
<A>
<A1>
<A2>Hi</A2>
</A1>
<A>
<B>
<B1></B1>
<B2>100</B2>
</B>
<A>
<A1>
<A2>Hello</A2>
</A1>
<A>
<B>
<B1>1000</B1>
<B2></B2>
</B>
likewise this goes more than 10 blocks. Now my java code able to read one by one that is first reads all after that reads tag.
Code:
public class XMLParse {
static Document doc;
public static void main(String argv[]) {
try {
File file = new File("/home/dev042/Desktop/xxx.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("A");
System.out.println("Information of all Balence Sheet");
int count = nodeLst.getLength();
String name;
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("A1");
for(int i =0; i < fstNmElmntLst.getLength(); i++ )
{
Node lst = fstNmElmntLst.item(i);
if(lst.getNodeType() == Node.ELEMENT_NODE)
{
Element fsttravel = (Element) lst;
NodeList secNmElt = fsttravel.getElementsByTagName("*");
name = secNmElt.item(0).getTextContent();
System.out.println("Name : " + name);
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
String amt;
double amount;
NodeList nodeLst = doc.getElementsByTagName("B");
int coun = nodeLst.getLength();
for (int s = 0; s < nodeLst.getLength(); s++) {
Node secNode = nodeLst.item(s);
if (secNode.getNodeType() == Node.ELEMENT_NODE) {
try
{
Element amtval = (Element) secNode;
NodeList secval = amtval.getElementsByTagName("B1");
amt = secval.item(0).getTextContent();
//amount = Double.parseDouble(amt);
System.out.println("SubAmt :" + amt);
NodeList lstNmElmntLst = amtval.getElementsByTagName("B2");
amt = lstNmElmntLst.item(0).getTextContent();
System.out.println("MainAmt : " +amt);
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
}
}
current output:
Hi
Hello
100
1000
I want to read the tags alternatively. then only i can able map the values. How can i read these tags alternatively. output should be like this
Hi 100
Hello 1000
Kindly help me out of it.
Thanks in advance..
I think you need to filter only tags so that your parser will fetch only tags.For this you can use XPath.This is an examples here:
http://www.roseindia.net/tutorials/xPath/java-xpath.shtml

Categories