How to browse and to display XML content with Java - java
I have a problem in Java with DOM...
Here is the XML code :
<?xml version="1.0" encoding="UTF-8"?>
<bib>
<domain>
<title>Specifications</title>
<bib_ref>
<year>March 2000</year>
<title>MOF 1.3</title>
<author>OMG</author>
<weblink>D:\SALIM\Docs\Specifications\MOF1_3.pdf</weblink>
</bib_ref>
<bib_ref>
<year>August 2002</year>
<title>IDLto Java LanguageMapping Specification</title>
<author>OMG</author>
<weblink>D:\SALIM\Docs\Specifications\IDL2Java.pdf</weblink>
</bib_ref>
<bib_ref>
<year>1999</year>
<title>XML Metadata Interchange (XMI) Version 1.1</title>
<author>OMG</author>
<weblink>D:\SALIM\Docs\Specifications\xmi-1.1.pdf</weblink>
</bib_ref>
<bib_ref>
<year>2002</year>
<title>XML Metadata Interchange (XMI) Version 2</title>
<author>"OMG</author>
<weblink>D:\SALIM\Docs\Specifications\XMI2.pdf</weblink>
</bib_ref>
<bib_ref>
<year>2002</year>
<title>XMI Version 1Production of XML Schema Specification</title>
<author>OMG</author>
<weblink>D:\SALIM\Docs\Specifications\XMI1XSD.pdf</weblink>
</bib_ref>
<bib_ref>
<year>2002</year>
<title>EDOC</title>
<author>OMG</author>
<weblink>D:\SALIM\Docs\Specifications\EDOC02-02-05.pdf</weblink>
</bib_ref>
</domain>
<domain>
<title>Theses</title>
<bib_ref>
<year>Octobre 2001</year>
<title>Echanges de Spécifications Hétérogènes et Réparties</title>
<author>Xavier Blanc</author>
<weblink>D:\SALIM\Docs\Theses\TheseXavier.pdf</weblink>
</bib_ref>
<bib_ref>
<year>Janvier 2001</year>
<title>Composition of Object-Oriented Software Design Models</title>
<author>Siobhan Clarke</author>
<weblink>D:\SALIM\Docs\Theses\SClarkeThesis.pdf</weblink>
</bib_ref>
......
......
After, in Java main function, I call the dispContent function which is just there:
public void dispContent (Node n)
{
String domainName = null;
// we are in an element node
if (n instanceof Element) {
Element e = ((Element) n);
// domain title
if (e.getTagName().equals("title") && e.getParentNode().getNodeName().equals("domain")) {
domainName = e.getTextContent();
DomaineTemplate(domainName);
}
else if (e.getTagName().equals("bib_ref")) {
NodeList ref = e.getChildNodes();
for (int i = 0; i < ref.getLength(); i++) {
Node temp = (Node) ref.item(i);
if (temp.getNodeType() == Node.ELEMENT_NODE) {
if (temp.getNodeType() == org.w3c.dom.Node.TEXT_NODE)
continue;
out.println(temp.getNodeName() + " : " + temp.getTextContent() + "\n");
}
}
}
else {
NodeList sub = n.getChildNodes();
for(int i=0; (i < sub.getLength()); i++)
dispContent(sub.item(i));
}
}
/*else if (n instanceof Document) {
NodeList fils = n.getChildNodes();
for(int i=0; (i < fils.getLength()); i++) {
dispContent(fils.item(i));
}
}*/
}
The "domaineTemplate" function just displays its parameter!
My problem happens when I browse the "bib_ref" tag in Java. For each "bib_ref" loop, it displays all the contents of all "bib_ref" tags... in one line! I want to display only one content (year, title, author and weblink tag) per "bib_ref".
Here is what it is displaying at the moment when I browse bib_ref :
Specifications
year : March 2000 title : MOF 1.3 author : OMG weblink : D:\SALIM\Docs\Specifications\MOF1_3.pdf year : August 2002 title : IDLto Java LanguageMapping Specification author : OMG weblink : D:\SALIM\Docs\Specifications\IDL2Java.pdf year : 1999 title : XML Metadata Interchange (XMI) Version 1.1 author : OMG weblink : D:\SALIM\Docs\Specifications\xmi-1.1.pdf year : 2002 title : XML Metadata Interchange (XMI) Version 2 author : OMG weblink : D:\SALIM\Docs\Specifications\XMI2.pdf year : 2002 title : XMI Version 1Production of XML Schema Specification author : OMG weblink : D:\SALIM\Docs\Specifications\XMI1XSD.pdf year : 2002 title : EDOC author : OMG weblink : D:\SALIM\Docs\Specifications\EDOC02-02-05.pdf
Theses
year : Octobre 2001 title : Echanges de Sp�cifications H�t�rog�nes et R�parties author : Xavier Blanc weblink : D:\SALIM\Docs\Theses\TheseXavier.pdf year : Janvier 2001 title : Composition of Object-Oriented Software Design Models author : Siobhan Clarke weblink : D:\SALIM\Docs\Theses\SClarkeThesis.pdf year : Juin 2002 title : Contribution � la repr�sentation de processu par des techniques de m�ta mod�lisation author : Erwan Breton weblink : D:\SALIM\Docs\Theses\ErwanBretonThesis.pdf year : Octobre 2000 title : Technique de Mod�lisation et de M�ta mod�lisation author : Richard Lemesle weblink : D:\SALIM\Docs\Theses\RichardLemesle.pdf year : Juillet 2002 title : Utilsation d'agents mobiles pour la construction des services distribu�s author : Siegfried Rouvrais weblink : D:\SALIM\Docs\Theses\theserouvrais.pdf
...
...
Can you help me ?
I'm just a beginner in xml with java and I'm searching some solution for about 3 hours... Thank's a lot!
I called dispContent(doc.getFirstChild()); where doc is the Document with your given xml file contents.
Assumptions: out.println() is System.out.println() and DomaineTemplate(domainName); adds a newline (based on your output provided)
I get the following print out in the console:
Specifications
year : March 2000
title : MOF 1.3
author : OMG
weblink : D:\SALIM\Docs\Specifications\MOF1_3.pdf
year : August 2002
title : IDLto Java LanguageMapping Specification
author : OMG
weblink : D:\SALIM\Docs\Specifications\IDL2Java.pdf
year : 1999
title : XML Metadata Interchange (XMI) Version 1.1
author : OMG
weblink : D:\SALIM\Docs\Specifications\xmi-1.1.pdf
year : 2002
title : XML Metadata Interchange (XMI) Version 2
author : "OMG
weblink : D:\SALIM\Docs\Specifications\XMI2.pdf
year : 2002
title : XMI Version 1Production of XML Schema Specification
author : OMG
weblink : D:\SALIM\Docs\Specifications\XMI1XSD.pdf
year : 2002
title : EDOC
author : OMG
weblink : D:\SALIM\Docs\Specifications\EDOC02-02-05.pdf
Theses
year : Octobre 2001
title : Echanges de Spécifications Hétérogènes et Réparties
author : Xavier Blanc
weblink : D:\SALIM\Docs\Theses\TheseXavier.pdf
year : Janvier 2001
title : Composition of Object-Oriented Software Design Models
author : Siobhan Clarke
weblink : D:\SALIM\Docs\Theses\SClarkeThesis.pdf
If you're having an issue with "\n" creating a new line, you can try using what the System uses:
public static final String NEW_LINE = System.getProperty("line.separator");
If you don't want the new lines between each line of the "bib_ref" node's children print outs, change:
else if (e.getTagName().equals("bib_ref")) {
NodeList ref = e.getChildNodes();
for (int i = 0; i < ref.getLength(); i++) {
Node temp = (Node) ref.item(i);
if (temp.getNodeType() == Node.ELEMENT_NODE) {
if (temp.getNodeType() == org.w3c.dom.Node.TEXT_NODE)
continue;
out.println(temp.getNodeName() + " : " + temp.getTextContent() + "\n");
}
}
}
to:
else if (e.getTagName().equals("bib_ref")) {
NodeList ref = e.getChildNodes();
for (int i = 0; i < ref.getLength(); i++) {
Node temp = (Node) ref.item(i);
if (temp.getNodeType() == Node.ELEMENT_NODE) {
if (temp.getNodeType() == org.w3c.dom.Node.TEXT_NODE)
continue;
// Removed "\n":
out.println(temp.getNodeName() + " : " + temp.getTextContent());
}
}
// Added out.println();
out.println();
}
Results:
Specifications
year : March 2000
title : MOF 1.3
author : OMG
weblink : D:\SALIM\Docs\Specifications\MOF1_3.pdf
year : August 2002
title : IDLto Java LanguageMapping Specification
author : OMG
weblink : D:\SALIM\Docs\Specifications\IDL2Java.pdf
year : 1999
title : XML Metadata Interchange (XMI) Version 1.1
author : OMG
weblink : D:\SALIM\Docs\Specifications\xmi-1.1.pdf
year : 2002
title : XML Metadata Interchange (XMI) Version 2
author : "OMG
weblink : D:\SALIM\Docs\Specifications\XMI2.pdf
year : 2002
title : XMI Version 1Production of XML Schema Specification
author : OMG
weblink : D:\SALIM\Docs\Specifications\XMI1XSD.pdf
year : 2002
title : EDOC
author : OMG
weblink : D:\SALIM\Docs\Specifications\EDOC02-02-05.pdf
Theses
year : Octobre 2001
title : Echanges de Spécifications Hétérogènes et Réparties
author : Xavier Blanc
weblink : D:\SALIM\Docs\Theses\TheseXavier.pdf
year : Janvier 2001
title : Composition of Object-Oriented Software Design Models
author : Siobhan Clarke
weblink : D:\SALIM\Docs\Theses\SClarkeThesis.pdf
Of course, now I see you have tagged your question with html and your code has nothing to do with html so far. So I asume out.println is some OutputStream for a Servlet and you're trying to Output html.
So the println linebreak, and the "\n" linebreaks are just available in the html sourcecode. The browser will skip this.
Change this line
out.println(temp.getNodeName() + " : " + temp.getTextContent() +
"\n");
to
out.println(temp.getNodeName() + " : " + temp.getTextContent() + "< br
/>");
and a servlet should output just fine with the linebreaks.
Related
Parsing the multilevel XML File with Java - Dom Parser
I have this xml file that contains 3 categories:employee_list, position_details and employee_info. <?xml version="1.0" encoding="UTF-8"?> <employee> <employee_list> <employee ID="1"> <firstname>Andrei</firstname> <lastname>Rus</lastname> <age>23</age> <position-skill ref="Java"/> <detail-ref ref="AndreiR"/> </employee> <employee ID="2"> <firstname>Ion</firstname> <lastname>Popescu</lastname> <age>25</age> <position-skill ref="Python"/> <detail-ref ref="IonP"/> </employee> <employee ID="3"> <firstname>Georgiana</firstname> <lastname>Domide</lastname> <age>33</age> <position-skill ref="C"/> <detail-ref ref="GeorgianaD"/> </employee> </employee_list> <position_details> <position ID="Java"> <role>Junior Developer</role> <skill_name>Java</skill_name> <experience>1</experience><!-- years of experience --> </position> <position ID="Python"> <role>Developer</role> <skill_name>Python</skill_name> <experience>3</experience> </position> <position ID="C"> <role>Senior Developer</role> <skill_name>C</skill_name> <experience>5</experience> </position> </position_details> <employee_info> <detail ID="AndreiR"> <username>AndreiR</username> <residence>Timisoara</residence> <yearOfBirth>1999</yearOfBirth> <phone>0</phone> </detail> <detail ID="IonP"> <username>IonP</username> <residence>Timisoara</residence> <yearOfBirth>1997</yearOfBirth> <phone>0</phone> </detail> <detail ID="GeorgianaD"> <username>GeorgianaD</username> <residence>Arad</residence> <yearOfBirth>1989</yearOfBirth> <phone>0</phone> </detail> </employee_info> </employee> I would like to write java code for all 3 categories, but so far I have only managed to get past the first category (employee_list). When I try to retrieve information from the position_list or employee_info category, the program fails to find information according to each category. I wrote the Java code for the 3 categories and the result looks like this: package Dom; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.util.Scanner; public class main { public static void main(String[] args) { try { File xmlDoc = new File("employees.xml"); DocumentBuilderFactory dbFact = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuild = dbFact.newDocumentBuilder(); Document doc = dBuild.parse(xmlDoc); //Citim radacina // doc localizeaza radacina da numele ei System.out.println("Root element: " + doc.getDocumentElement().getNodeName()); System.out.println("-----------------------------------------------------------------------------"); //citim un array de studenti pe care il denumim NodeList NodeList nList = doc.getElementsByTagName("employee"); System.out.println("Total Category inside = " + nList.getLength()); System.out.println("-----------------------------------------------------"); for(int i = 0 ; i<nList.getLength();i++) { Node nNode = nList.item(i); //System.out.println("Node name: " + nNode.getNodeName()+" " + (i+1)); if(nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Person id#: " + eElement.getAttribute("id")); System.out.println("Person Last Name: " + eElement.getElementsByTagName("lastname").item(0).getTextContent()); System.out.println("Person First name: " + eElement.getElementsByTagName("firstname").item(0).getTextContent()); System.out.println("Person Age: " + eElement.getElementsByTagName("age").item(0).getTextContent()); System.out.println("--------------------------------------------------------------------------"); } } System.out.println("============================================================================================="); nList = doc.getElementsByTagName("position"); System.out.println("Total Category inside = " + nList.getLength()); System.out.println("-----------------------------------------------------"); for(int i = 0 ; i<nList.getLength();i++) { Node nNode = nList.item(i); //System.out.println("Node name: " + nNode.getNodeName()+" " + (i+1)); if(nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Role: " + eElement.getElementsByTagName("role").item(0).getTextContent()); System.out.println("Skill: "+ eElement.getElementsByTagName("skill_name").item(0).getTextContent()); System.out.println("Experience: "+ eElement.getElementsByTagName("experience").item(0).getTextContent()); System.out.println("--------------------------------------------------------------------------"); } } System.out.println("============================================================================================="); nList = doc.getElementsByTagName("detail"); System.out.println("Total Category inside = " + nList.getLength()); System.out.println("-----------------------------------------------------"); for(int i = 0 ; i<nList.getLength();i++) { Node nNode = nList.item(i); //System.out.println("Node name: " + nNode.getNodeName()+" " + (i+1)); if(nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; System.out.println("Person with username: " + eElement.getElementsByTagName("username").item(0).getTextContent()); System.out.println("Username: " + eElement.getElementsByTagName("username").item(0).getTextContent()); System.out.println("Residence: "+ eElement.getElementsByTagName("residence").item(0).getTextContent()); System.out.println("Year of birth: "+ eElement.getElementsByTagName("yearOfBirth").item(0).getTextContent()); System.out.println("Phone: "+ eElement.getElementsByTagName("phone").item(0).getTextContent()); System.out.println("--------------------------------------------------------------------------"); } } }catch(Exception e) { } } } output: Root element: employee ----------------------------------------------------------------------------- Total Category inside = 4 ----------------------------------------------------- Person id#: Person Last Name: Rus Person First name: Andrei Person Age: 23 -------------------------------------------------------------------------- Person id#: Person Last Name: Rus Person First name: Andrei Person Age: 23 -------------------------------------------------------------------------- Person id#: Person Last Name: Popescu Person First name: Ion Person Age: 25 -------------------------------------------------------------------------- Person id#: Person Last Name: Domide Person First name: Georgiana Person Age: 33 -------------------------------------------------------------------------- ============================================================================================= Total Category inside = 3 ----------------------------------------------------- Role: Junior Developer Skill: Java Experience: 1 -------------------------------------------------------------------------- Role: Developer Skill: Python Experience: 3 -------------------------------------------------------------------------- Role: Senior Developer Skill: C Experience: 5 -------------------------------------------------------------------------- ============================================================================================= Total Category inside = 3 ----------------------------------------------------- Person with username: AndreiR Username: AndreiR Residence: Timisoara Year of birth: 1999 Phone: 0 -------------------------------------------------------------------------- Person with username: IonP Username: IonP Residence: Timisoara Year of birth: 1997 Phone: 0 -------------------------------------------------------------------------- Person with username: GeorgianaD Username: GeorgianaD Residence: Arad Year of birth: 1989 Phone: 0 -------------------------------------------------------------------------- Is there any possibility that the output could be slightly more grouped, in the following form for each person: PersonId firstname lastname age role skill_name experience username residence yearOfBirth phone
But you've basically done it already, you wrote the code for the three categories. "Failing to find information according to each category" might mean that the output is not the desired output. The reason could be that Document.getElementsByTagName() searches globally for all elements that have the name passed as the argument. As your root element too is named employee, it's included as an additional Node in your NodeList on doc.getElementsByTagName("employee"), which btw. doesn't have an ID attribute of it's own (note: these are case-sensitive). Hence a "Total Category inside = 4". If you then do getElementsByTagName("lastname") on this first Node/Element that's the root, sure enough, it has a <lastname/> element below it, just not as a direct child, but two levels down, the element of the first "actual"/desired <employee/>. So what you probably want to do is to not search for your element names globally, but in the local context of the category, as you already do successfully elsewhere inside the loops. Maybe just change NodeList nList = doc.getElementsByTagName("employee"); to NodeList nList = doc.getElementsByTagName("employee_list"); nList = ((Element)nList.item(0)).getElementsByTagName("employee"); for the employee_list category, and likewise for the other categories. In order to group records more nicely, you don't need to output/print them immediately. You can copy/store the values you get from the DOM in the members of an object of a class you could define, or make a more generic class which stores the field values in a List that contains a Map, or something like that. With such, you can iterate/loop over the objects or list you created, and output/print the field values in your preferred order.
RestAssured - How to read an array element from the json response
#Test public void getFirstRequestVerifyResponse() { String idToValidate= "5ea6fe53e4b09a8de7aeb19d"; System.out.println("Response :" + response.asString()); System.out.println("id : " + response.asString().contains(idToValidate)); } I am getting the following response. Response :[{"id":"5ea6fe53e4b09a8de7aeb19d","contents":[{"pageSize":6,"source":"BE","packageId":"ATV_PACKAGE_1538998610009"}],"name":"FEATURE BANNER","format":{"lsTy":"DEFAULT","showAll":false,"autoCarousel":false,"ty":"BANNER","action":{"source":"BE","contentId":"ATV_PACKAGE_1538998610009","t":"Play","st":"PLAY"},"contentAction":{"meta":{}}}},{"id":"5ac37644e4b03f23a4a705dc","contents":[],"name":"MastheadAd","format":{"lsTy":"DEFAULT","ty":"NATIVE_MASTHEAD_AD","action":{"source":"BE","st":"CUSTOM","sTy":"CUSTOM_AMAZON"},"contentAction":{"sTy":"CUSTOM_AMAZON","meta":{}},"lds":[],"adId":"/417241724/tv_native_masthead_plain_prod","tId":["11767767","11768950"]}},{"id":"5d63ca1de4b088013a6236b3","contents":[{"pageSize":50,"source":"RM","packageId":"dummy"}],"name":"Recommended Movies","format":{"lsTy":"DEFAULT","showAll":false,"ty":"MOVIE_NOLOGO","contentAction":{"meta":{"sourceName":"cf_movies_home"}}}},{"id":"5d63ca1de4b088013a6236b2","contents":[{"pageSize":50,"source":"RM","packageId":"dummy"}],"name":"Recommended TV Shows","format":{"lsTy":"DEFAULT","showAll":false,"ty":"MOVIE_NOLOGO","contentAction":{"meta":{"sourceName":"cf_tvshow_home"}}}},{"id":"5ae6b962e4b088c1fe893389","contents":[{"pageSize":20,"source":"MW","packageId":"ATV_PACKAGE_1524207345077","ty":"LIVE"}],"name":"LIVE NEWS","format":{"lsTy":"DEFAULT","showAll":false,"bgImgUrl":"","ty":"TVSHOW_LOGO_43","action":{"color":"#ff0000","pageId":"live_TV","t":"More","st":"LANDING"},"contentAction":{"meta":{}},"t":"LIVE NEWS"}},{"id":"5e74bffce4b0e60befa24bbb","contents":[{"pageSize":10,"source":"BE","packageId":"ATV_PACKAGE_1568185919253"}],"name":"Your Daily News in 30 Secs HIndi","format":{"lsTy":"DEFAULT","showAll":false,"bgImgUrl":"https://image.airtel.tv/pages/rails/5d2d6945e4b06e55de6b8cfe/editorji_highlightrail_background.jpg","ty":"TVSHOW_BIG_43","action":{"source":"BE","packageId":"ATV_PACKAGE_1568185919253","listingType":"TVSHOW_BIG_43","t":"More","st":"LISTING"},"contentAction":{"meta":{}},"t":"Your Daily News in 30 Secs"}},{"id":"5d9ec624e4b0499e024c99c6","contents":[{"pageSize":10,"source":"BE","packageId":"ATV_PACKAGE_1570605272423"}],"name":"Learn with Xstream","format":{"lsTy":"EXPLORE","ty":"CUSTOM","action":{"st":"DEFAULT"},"contentAction":{"source":"BE","pageId":"ATV_PACKAGE_1570605272423","st":"CUSTOM","sTy":"LISTING","meta":{}},"lds":[],"t":"Learn with Xstream"}},{"id":"5c78ce19e4b0d4a057339b17","contents":[{"pageSize":25,"source":"BE","packageId":"ATV_PACKAGE_1540027201907"}],"name":"MOST WATCHED HOLLYWOOD MOVIES","format":{"lsTy":"DEFAULT","showAll":false,"ty":"MOVIE_NOLOGO","action":{"color":"#a1ec00","source":"BE","packageId":"ATV_PACKAGE_1540027201907","listingType":"MOVIE_NOLOGO","t":"More","st":"LISTING"},"contentAction":{"meta":{}},"t":"Most Watched Hollywood Movies"}},{"id":"5e789319e4b032c54a8f0646","contents":[],"name":"Family Movie Card - English + Hindi","format":{"lsTy":"DEFAULT","ty":"CARD_NOTITILE_169","action":{"source":"MW","channelId":"MWTV_LIVETVCHANNEL_10000000060880000","t":"Play","st":"PLAY","meta":{"k":"1"},"ty":"LIVE"},"contentAction":{"meta":{}},"lds":[],"img":"https://image.airtel.tv/pages/rails/5e9083e8e4b0cff1aeeb2d58/Swami_Ramdev_New.jpg"}},{"id":"5d64b170e4b067b667714913","contents":[{"pageSize":12,"source":"BE","packageId":"ATV_PACKAGE_1566817268865"}],"name":"BEST HOLLYWOOD Series","format":{"lsTy":"DEFAULT","showAll":false,"ty":"MOVIE_NOLOGO","action":{"source":"BE","packageId":"ATV_PACKAGE_1566817268865","listingType":"MOVIE_NOLOGO","t":"More","st":"LISTING"},"contentAction":{"meta":{}},"t":"Best Hollywood Movie Series"}},{"id":"5e7892e6e4b032c54a8f0645","contents":[],"name":"Nostalgia Movie Card - English + Hindi","format":{"lsTy":"DEFAULT","ty":"CARD_NOTITILE_169","hIcon":"https://image.airtel.tv/pages/rails/5e7892e6e4b032c54a8f0645/ic_cplogo_hooq.png","action":{"source":"BE","packageId":"ATV_PACKAGE_1584939335512","listingType":"MOVIE_NOLOGO","t":"More","st":"LISTING","meta":{"A":"1"}},"contentAction":{"meta":{}},"lds":[],"img":"https://image.airtel.tv/pages/rails/5e7892e6e4b032c54a8f0645/NOSTALGIA-MOVIES-1032X576_(1).jpg"}},{"id":"5e99b557e4b0c3a92edf1ee7","contents":[],"name":"Wynk Music - Vishal Mishra - Live Concert Card Testing","format":{"lsTy":"DEFAULT","ty":"CARD_NOTITILE_169","action":{"source":"BE","contentId":"MWTV_LIVETVCHANNEL_10000000060880000","t":"Play","st":"PLAY","meta":{"k":"1"}},"contentAction":{"meta":{}},"lds":[],"img":"https://image.airtel.tv/pages/rails/5e99b010e4b03c81436668d3/1-Lohri-1032X576.jpg"}},{"id":"5ea70c25e4b0cea120315672","contents":[],"name":"Astha Gill Type Form Card Test","format":{"lsTy":"DEFAULT","ty":"PRODUCT_CARD","action":{"url":"https://wynkproduct.typeform.com/to/DesNW4","t":"Play","st":"WEBVIEW","meta":{"redirectType":"REDIRECT_TV","redirectDeeplink":"https://wynkproduct.typeform.com/to/DesNW4"}},"contentAction":{"meta":{}},"lds":[],"img":"https://image.airtel.tv/pages/rails/5ea70c25e4b0cea120315672/2-Badla-1032X576_(1).jpg"}},{"id":"5ea711a0e4b0cea120315674","contents":[],"name":"Aastha Gill - Card - Test","format":{"lsTy":"DEFAULT","ty":"CARD_NOTITILE_169","action":{"source":"MW","channelId":"MWTV_LIVETVCHANNEL_10000000060880000","t":"Play","st":"PLAY","ty":"LIVE"},"contentAction":{"meta":{}},"lds":[],"img":"https://image.airtel.tv/pages/rails/5ea711a0e4b0cea120315674/2-Badla-1032X576_(1).jpg"}},{"id":"5ea70fcfe4b0cea120315673","contents":[],"name":"test_card_ndtv","format":{"lsTy":"DEFAULT","ty":"CARD_NOTITILE_169","action":{"source":"MW","channelId":"MWTV_LIVETVCHANNEL_10000000060880000","t":"NDTV","st":"PLAY","ty":"LIVE"},"contentAction":{"meta":{}},"lt":"","ds":"","lds":[],"img":"https://image.airtel.tv/pages/rails/5ea70fcfe4b0cea120315673/photo-1549465220-1a8b9238cd48.jpeg"}}] How can I get the "packageId" from the response for this idToValidate. Please help me on it.
You can use JsonPath String res = "Response :[{"id":"5ea6fe53e4b09a8de7aeb19d","contents":[{"pageSize":6,"source":"BE","packageId":"ATV_PACKAGE_1538998610009"}],"name":"FEATURE BANNER","format":{"lsTy":"DEFAULT","showAll":false,"autoCarousel":false,"ty":"BANNER","action":{"source":"BE","contentId":"ATV_PACKAGE_1538998610009","t":"Play","st":"PLAY"},"contentAction":{"meta":{}}}},{"id":"5ac37644e4b03f23a4a705dc","contents":[],"name":"MastheadAd","format":{"lsTy":"DEFAULT","ty":"NATIVE_MASTHEAD_AD","action":{"source":"BE","st":"CUSTOM","sTy":"CUSTOM_AMAZON"},"contentAction":{"sTy":"CUSTOM_AMAZON","meta":{}},"lds":[],"adId":"/417241724/tv_native_masthead_plain_prod","tId":["11767767","11768950"]}},{"id":"5d63ca1de4b088013a6236b3","contents":[{"pageSize":50,"source":"RM","packageId":"dummy"}],"name":"Recommended Movies","format":{"lsTy":"DEFAULT","showAll":false,"ty":"MOVIE_NOLOGO","contentAction":{"meta":{"sourceName":"cf_movies_home"}}}},{"id":"5d63ca1de4b088013a6236b2","contents":[{"pageSize":50,"source":"RM","packageId":"dummy"}],"name":"Recommended TV Shows","format":{"lsTy":"DEFAULT","showAll":false,"ty":"MOVIE_NOLOGO","contentAction":{"meta":{"sourceName":"cf_tvshow_home"}}}},{"id":"5ae6b962e4b088c1fe893389","contents":[{"pageSize":20,"source":"MW","packageId":"ATV_PACKAGE_1524207345077","ty":"LIVE"}],"name":"LIVE NEWS","format":{"lsTy":"DEFAULT","showAll":false,"bgImgUrl":"","ty":"TVSHOW_LOGO_43","action":{"color":"#ff0000","pageId":"live_TV","t":"More","st":"LANDING"},"contentAction":{"meta":{}},"t":"LIVE NEWS"}},{"id":"5e74bffce4b0e60befa24bbb","contents":[{"pageSize":10,"source":"BE","packageId":"ATV_PACKAGE_1568185919253"}],"name":"Your Daily News in 30 Secs HIndi","format":{"lsTy":"DEFAULT","showAll":false,"bgImgUrl":"https://image.airtel.tv/pages/rails/5d2d6945e4b06e55de6b8cfe/editorji_highlightrail_background.jpg","ty":"TVSHOW_BIG_43","action":{"source":"BE","packageId":"ATV_PACKAGE_1568185919253","listingType":"TVSHOW_BIG_43","t":"More","st":"LISTING"},"contentAction":{"meta":{}},"t":"Your Daily News in 30 Secs"}},{"id":"5d9ec624e4b0499e024c99c6","contents":[{"pageSize":10,"source":"BE","packageId":"ATV_PACKAGE_1570605272423"}],"name":"Learn with Xstream","format":{"lsTy":"EXPLORE","ty":"CUSTOM","action":{"st":"DEFAULT"},"contentAction":{"source":"BE","pageId":"ATV_PACKAGE_1570605272423","st":"CUSTOM","sTy":"LISTING","meta":{}},"lds":[],"t":"Learn with Xstream"}},{"id":"5c78ce19e4b0d4a057339b17","contents":[{"pageSize":25,"source":"BE","packageId":"ATV_PACKAGE_1540027201907"}],"name":"MOST WATCHED HOLLYWOOD MOVIES","format":{"lsTy":"DEFAULT","showAll":false,"ty":"MOVIE_NOLOGO","action":{"color":"#a1ec00","source":"BE","packageId":"ATV_PACKAGE_1540027201907","listingType":"MOVIE_NOLOGO","t":"More","st":"LISTING"},"contentAction":{"meta":{}},"t":"Most Watched Hollywood Movies"}},{"id":"5e789319e4b032c54a8f0646","contents":[],"name":"Family Movie Card - English + Hindi","format":{"lsTy":"DEFAULT","ty":"CARD_NOTITILE_169","action":{"source":"MW","channelId":"MWTV_LIVETVCHANNEL_10000000060880000","t":"Play","st":"PLAY","meta":{"k":"1"},"ty":"LIVE"},"contentAction":{"meta":{}},"lds":[],"img":"https://image.airtel.tv/pages/rails/5e9083e8e4b0cff1aeeb2d58/Swami_Ramdev_New.jpg"}},{"id":"5d64b170e4b067b667714913","contents":[{"pageSize":12,"source":"BE","packageId":"ATV_PACKAGE_1566817268865"}],"name":"BEST HOLLYWOOD Series","format":{"lsTy":"DEFAULT","showAll":false,"ty":"MOVIE_NOLOGO","action":{"source":"BE","packageId":"ATV_PACKAGE_1566817268865","listingType":"MOVIE_NOLOGO","t":"More","st":"LISTING"},"contentAction":{"meta":{}},"t":"Best Hollywood Movie Series"}},{"id":"5e7892e6e4b032c54a8f0645","contents":[],"name":"Nostalgia Movie Card - English + Hindi","format":{"lsTy":"DEFAULT","ty":"CARD_NOTITILE_169","hIcon":"https://image.airtel.tv/pages/rails/5e7892e6e4b032c54a8f0645/ic_cplogo_hooq.png","action":{"source":"BE","packageId":"ATV_PACKAGE_1584939335512","listingType":"MOVIE_NOLOGO","t":"More","st":"LISTING","meta":{"A":"1"}},"contentAction":{"meta":{}},"lds":[],"img":"https://image.airtel.tv/pages/rails/5e7892e6e4b032c54a8f0645/NOSTALGIA-MOVIES-1032X576_(1).jpg"}},{"id":"5e99b557e4b0c3a92edf1ee7","contents":[],"name":"Wynk Music - Vishal Mishra - Live Concert Card Testing","format":{"lsTy":"DEFAULT","ty":"CARD_NOTITILE_169","action":{"source":"BE","contentId":"MWTV_LIVETVCHANNEL_10000000060880000","t":"Play","st":"PLAY","meta":{"k":"1"}},"contentAction":{"meta":{}},"lds":[],"img":"https://image.airtel.tv/pages/rails/5e99b010e4b03c81436668d3/1-Lohri-1032X576.jpg"}},{"id":"5ea70c25e4b0cea120315672","contents":[],"name":"Astha Gill Type Form Card Test","format":{"lsTy":"DEFAULT","ty":"PRODUCT_CARD","action":{"url":"https://wynkproduct.typeform.com/to/DesNW4","t":"Play","st":"WEBVIEW","meta":{"redirectType":"REDIRECT_TV","redirectDeeplink":"https://wynkproduct.typeform.com/to/DesNW4"}},"contentAction":{"meta":{}},"lds":[],"img":"https://image.airtel.tv/pages/rails/5ea70c25e4b0cea120315672/2-Badla-1032X576_(1).jpg"}},{"id":"5ea711a0e4b0cea120315674","contents":[],"name":"Aastha Gill - Card - Test","format":{"lsTy":"DEFAULT","ty":"CARD_NOTITILE_169","action":{"source":"MW","channelId":"MWTV_LIVETVCHANNEL_10000000060880000","t":"Play","st":"PLAY","ty":"LIVE"},"contentAction":{"meta":{}},"lds":[],"img":"https://image.airtel.tv/pages/rails/5ea711a0e4b0cea120315674/2-Badla-1032X576_(1).jpg"}},{"id":"5ea70fcfe4b0cea120315673","contents":[],"name":"test_card_ndtv","format":{"lsTy":"DEFAULT","ty":"CARD_NOTITILE_169","action":{"source":"MW","channelId":"MWTV_LIVETVCHANNEL_10000000060880000","t":"NDTV","st":"PLAY","ty":"LIVE"},"contentAction":{"meta":{}},"lt":"","ds":"","lds":[],"img":"https://image.airtel.tv/pages/rails/5ea70fcfe4b0cea120315673/photo-1549465220-1a8b9238cd48.jpeg"}}]"; Code : JsonPath js = new JsonPath(res); String idToValidate = "5ae6b962e4b088c1fe893389"; System.out.println("id : " + res.contains(idToValidate)); String packageId = js.get("find {it.id =='"+idToValidate+"'}.contents.packageId").toString(); System.out.println("PackageID : " + packageId); Output : ID : true PackageID : [ATV_PACKAGE_1524207345077] Alternative : String output = given().when().get(url).then().extract().body().jsonPath().get("find {it.id =='"+idToValidate+"'}.contents.packageId").toString(); System.out.println(output);
How to read the contents of (.bib) file format using Java
I need to read .bib file and insert it tags into an objects of bib-entries the file is big (almost 4000 lines) , so my first question is what to use (bufferrReader or FileReader) the general format is #ARTICLE{orleans01DJ, author = {Doug Orleans and Karl Lieberherr}, title = {{{DJ}: {Dynamic} Adaptive Programming in {Java}}}, journal = {Metalevel Architectures and Separation of Crosscutting Concerns 3rd Int'l Conf. (Reflection 2001), {LNCS} 2192}, year = {2001}, pages = {73--80}, month = sep, editor = {A. Yonezawa and S. Matsuoka}, owner = {Administrator}, publisher = {Springer-Verlag}, timestamp = {2009.03.09} } #ARTICLE{Ossher:1995:SOCR, author = {Harold Ossher and Matthew Kaplan and William Harrison and Alexander Katz}, title = {{Subject-Oriented Composition Rules}}, journal = {ACM SIG{\-}PLAN Notices}, year = {1995}, volume = {30}, pages = {235--250}, number = {10}, month = oct, acknowledgement = {Nelson H. F. Beebe, University of Utah, Department of Mathematics, 110 LCB, 155 S 1400 E RM 233, Salt Lake City, UT 84112-0090, USA, Tel: +1 801 581 5254, FAX: +1 801 581 4148, e-mail: \path|beebe#math.utah.edu|, \path|beebe#acm.org|, \path|beebe#computer.org| (Internet), URL: \path|http://www.math.utah.edu/~beebe/|}, bibdate = {Fri Apr 30 12:33:10 MDT 1999}, coden = {SINODQ}, issn = {0362-1340}, keywords = {ACM; object-oriented programming systems; OOPSLA; programming languages; SIGPLAN}, owner = {Administrator}, timestamp = {2009.02.26} } As you can see , there are some entries that have more than line, entries that end with } entries that end with }, or }}, Also , some entries have {..},{..}.. in the middle so , i am a little bit confused on how to start reading this file and how to get these entries and manipulate them. Any help will be highly appreciated.
We currently discuss different options at JabRef. These are the current options: JBibTeX ANTLRv3 Grammar JabRef's BibtexParser.java
Parse Specific Elements DOM - Java
I believe this is a simple question but I am having trouble to find out how it works. That's the XML file (from www.w3schools.com): <?xml version="1.0" encoding="ISO-8859-1"?> <!-- Edited by XMLSpy® --> <bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="web"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> <book category="web" cover="paperback"> <title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> </bookstore> As you can see the book XQuery Kick Start has more than one author. But I cant find a way to get the right number of authors. Thats my code: public static void main(String argv[]) throws ParserConfigurationException, SAXException, IOException { File fXmlFile = new File("\books.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("book"); 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("Category : " + eElement.getAttribute("category")); System.out.println("Title : " + eElement.getElementsByTagName("title").item(0).getTextContent()); System.out.println("Author : " + eElement.getElementsByTagName("author").item(0).getTextContent()); System.out.println("Year : " + eElement.getElementsByTagName("year").item(0).getTextContent()); System.out.println("Price : " + eElement.getElementsByTagName("price").item(0).getTextContent()); } } But as Result I'll be getting only one author: Root element :bookstore ---------------------------- Current Element :book Categoria do Livro : cooking Titulo : Everyday Italian Autor : Giada De Laurentiis Ano : 2005 Price : 30.00 Current Element :book Categoria do Livro : children Titulo : Harry Potter Autor : J K. Rowling Ano : 2005 Price : 29.99 Current Element :book Categoria do Livro : web Titulo : XQuery Kick Start Autor : James McGovern Ano : 2003 Price : 49.99 Current Element :book Categoria do Livro : web Titulo : Learning XML Autor : Erik T. Ray Ano : 2003 Price : 39.95 Does anyone knows a good method to get the right number of elements? sorry about the long question, I didnt know how to express myself so I had to paste here *I'm new to DOM*
You're are getting the first author always, as you're retrieving the first item of the nodelist getElementsByTagName("author").item(0) Try iterating them, as there could be more than one for (int i = 0; i < eElement.getElementsByTagName("author").getLength(); i++) System.out.println("Author : " + eElement.getElementsByTagName("author").item(i).getTextContent());
ANTLR : AST, Java
I am trying to generate AST after parsing a HTML file. grammar XHTML2CSV; options { output=AST; ASTLabelType=CommonTree; } tokens { CELLULE; LIGNE; CELLULEG = '<td>'; CELLULED = '</td>'; DEBUTCOL = '<tr>'; FINCOL = '</tr>'; DTAB = '<table'; STAB = ' align=\"center\"'; FTAB = ' border=\"1\">'; FINTAB ='</table>'; ligne : DEBUTCOL cellule+ FINCOL -> ^(LIGNE cellule); cellule : CELLULEG CHAINE CELLULED -> ^(CELLULE CHAINE); And when I parse somthing like : <tr> <td>"Cellule 1"</td> <td>"Cellule 2"</td> <td>"Cellule 3"</td> </tr> I just get the tree : nil ---> LIGNE ---> CELLULE ---> "Cellule 1" How can I do to get all the children of LIGNE in the AST ? Thanks
It seems you forgot a + in your rewrite rule: ligne : DEBUTCOL cellule+ FINCOL -> ^(LIGNE cellule+) ; // ^ // | // +--- ici! FYI: there's an HTML grammar on the ANTLR website: http://www.antlr.org/grammar/HTML