dom parser getElement - java

I want to only get restaurants in beirut with dom parser please help
this is a part from my xml file :
city -> beirut->restaurants->restaurant->name->
tyr->restaurants->restaurant->name->
jbeil->restaurants->restaurant->name->
<restaurants>
<restaurant>
<name>
...
</restaurant>
</restaurants>
<restaurants>
<restaurant>
<name>
...
</restaurant>
</restaurants>
<restaurants>
<restaurant>
<name>
...
</restaurant>
</restaurants>
because this code give me all restaurants in all city's :
try {
File inputFile = new File("src/josephXml.xml");
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Restaurant");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
jTextArea1.append( "\n"+"Name : "+ eElement
.getElementsByTagName("name")
.item(0)
.getTextContent()+"\n "
, i only want restaurants in beirut please help

You use Restaurant, but your file uses restaurant. It's not OK, because case sensitive.
use XPath: you can select many things, it is very readable.
Replace this in your code:
XPath xPath = XPathFactory.newInstance().newXPath();
String expression="/city/beirut/restaurants/restaurant";
NodeList nList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);

Related

Get element with xml dom parser [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How to get restaurant name in jbeil only using xml DOM parser , please help :
And this is my XML file
<city>
<beirut>
<restaurant>
<name>sada</name>
</restaurant>
</beirut>
<jbeil>
<restaurant>
<name>sada</name>
</restaurant>
</jbeil>
<sour>
<restaurant>
<name>sada</name>
</restaurant>
</sour>
</city>
I want to get the name of restaurant in Jbeil using dom parser and this code give me restaurants name in all city's:
try {
File inputFile = new File("src/josephXml.xml");
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("Restaurant");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
jTextArea1.append( "\n"+"Name : "+ eElement
.getElementsByTagName("name")
.item(0)
.getTextContent()+"\n "
use XPath
many resources: http://viralpatel.net/blogs/java-xml-xpath-tutorial-parse-xml/
something like that (not tested)
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
XPath xPath =  XPathFactory.newInstance().newXPath();
String expression = "/city/jbeil/restaurant/name";
//read a string value
String thename= xPath.compile(expression).evaluate(xmlDocument);
Using the same code style as you and "only using xml DOM parser" get the jbeil and then the restaurant...
NodeList nList = doc.getElementsByTagName("jbeil");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
NodeList nList2 = eElement.getElementsByTagName("restaurant");
for (int n = 0; n < nList.getLength(); n++) {
Node nNode2 = nList2.item(n);
if (nNode2.getNodeType() == Node.ELEMENT_NODE) {
Element eElement2 = (Element) nNode;
System.out.println(eElement2.getElementsByTagName("name").item(0).getTextContent());
}
}
}
}
But I would go for the XPath answer...

update xml document using xpath

Hello this is my xml document :
<city>
<beirut>
<restaurant>
<name>sada</name>
</restaurant>
</beirut>
<jbeil>
<restaurant>
<name>toto</name>
<rating>4.3/5</rating>
</restaurant>
<restaurant>
<name>jojo</name>
<rating>4.3/5</rating>
</restaurant>
</jbeil>
<sour>
<restaurant>
<name>sada</name>
</restaurant>
</sour>
</city>
I want to update the rating of "jojo" restaurant in jbeil from 4.3/5 to 4.5/5 using xpath and netbeans please help ,
this code give the rating ,
try {
File inputFile = new File("src/xpath/josephXml.xml");
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/City/Jbeil/Restaurant";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node nNode = nodeList.item(i);
System.out.println("\nCurrent Element :"
+ nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("rating : "
+ eElement
.getElementsByTagName("rating")
.item(0)
.getTextContent());
and i want only to update the rating of restaurant in jbeil where name is "jojo" , please help
This is one possible XPath to find such restaurant named jojo in the city of jbeil and then return the corresponding rating element :
/city/jbeil/restaurant[name='jojo']/rating
Notice that XML & XPath are case-sensitive, so I used all lower-case characters in the above XPath to match the XML posted in this question.
I don't know much about Java, but quick searching over the internet* suggest something like this :
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/city/jbeil/restaurant[name='jojo']/rating";
Element e = (Element)xpath.evaluate(expression, doc, XPathConstant.NODE);
if (e != null)
e.setTextContent("4.5/5");
*) how to modify xml tag specific value in java?

How to print values within XML tag in java [duplicate]

This question already has answers here:
Get element name from XML in Java DOM
(3 answers)
Closed 8 years ago.
I never really know how to work with XML tags.How do I traverse the node and print particular node in the XML tag.Below is the XML file.
<Employees>
<Employee>
<Gender></Gender>
<Name>
<Firstname></Firstname>
<Lastname></Lastname>
</Name>
<Email></Email>
<Projects>
<Project></Project>
</Projects>
<PhoneNumbers>
<Home></Home>
<Office></Office>
</PhoneNumbers>
</Employee>
There is no data but this is the structure.I am using the following code to parse it partially.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document xmlDocument = builder.parse("employees.xml");
System.out.println(xmlDocument.getDocumentElement().getNodeName());
I would like to print the gender and lastname values.How do I parse the tag which is inside the Name tag which in turn the Name is inside the Employee tag.
Regards.
You should use XPATH. There is a good explanation in this post.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(<xpath_expression>);
Try this.
String expression = "/Employees/Employee/Gender"; //read Gender value
NodeList nList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
for (int j = 0; nList != null && j < nList.getLength(); j++) {
Node node = nList.item(j);
System.out.println("" + node.getFirstChild().getNodeValue());
}
expression = "/Employees/Employee/Name/Lastname"; //read Lastname value
nList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
for (int j = 0; nList != null && j < nList.getLength(); j++) {
Node node = nList.item(j);
System.out.println("" + node.getFirstChild().getNodeValue());
}

xml parsing with java

I'm new to xml parsing, I am trying to parse the following xml file using java.
<a>
<e class="object">
<amenities class="array">
<e class="object">
<id type="number">31</id>
<name type="string">Internet access available</name>
</e>
<e class="object">
<id type="number">9</id>
<name type="string">Business center</name>
</e>
</amenities>
<brands class="array">
<e class="object">
<code type="number">291</code>
<name type="string">Utell</name>
</e>
<e class="object">
<code type="number">72</code>
<name type="string">Best Western International</name>
</e>
</brands>
<hotels class="array">
<e class="object">
<addressLine1 type="string">4 Rue du Mont-Thabor</addressLine1>
<city type="string">Paris</city>
<name type="string">Renaissance Paris Vendome Hotel</name>
<starRating type="string">5</starRating>
</e>
<e class="object">
<addressLine1 type="string">35 Rue de Berri</addressLine1>
<city type="string">Paris</city>
<name type="string">Crowne Plaza Hotel PARIS-CHAMPS ELYSÉES</name>
<starRating type="string">5</starRating>
</e>
</hotels>
</e>
</a>
I only need to list the name tag info(which will be the Hotel name) for that I used following code but it resulted me not only the hotel info but also everything, can anyone please help me parsing this???
Thanks a lot!!!
Here is the java code I used
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("c:\\file.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("e");
System.out.println("-----------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Hotel Name : " + getTagValue("name",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();
}
}
You could use xpath to get all the name nodes:
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/hotels//name");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
Pavithira you can use xpath to get only the hotels, below is the main method which you can simple copy/paste at your code.
public static void main(String argv[]) {
try {
File fXmlFile = new File("c:\\file.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());
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//hotels/e");
NodeList nList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
System.out.println("-----------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Hotel Name : "
+ getTagValue("name", eElement));
}
}
} catch (Exception e) {
e.printStackTrace();
}
You are iterating over the 'e' nodes, so your loop will print out every node inside any 'e' node (which includes the (sub)root node!). Change your getElementsByTagName paramater to "name" if you only want to retrieve and print those nodes.

XML parser gives null element

When I try to parse a XML-file, it gives sometimes a null element by the title.
I think it has to do with HTML-tags '
How can I solve this problem?
I have the follow XML-file:
<item>
<title>' Nieuwe DVD '</title>
<description>tekst, tekst tekst</description>
<link>dvd.html</link>
<category>nieuws</category>
<pubDate>Sat, 1 Jan 2011 9:24:00 +0000</pubDate>
</item>
And the follow code to parse the xml-file:
//DocumentBuilderFactory, DocumentBuilder are used for
//xml parsing
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
//using db (Document Builder) parse xml data and assign
//it to Element
Document document = db.parse(is);
Element element = document.getDocumentElement();
//take rss nodes to NodeList
element.normalize();
NodeList nodeList = element.getElementsByTagName("item");
if (nodeList.getLength() > 0)
{
for (int i = 0; i < nodeList.getLength(); i++)
{
//take each entry (corresponds to <item></item> tags in
//xml data
Element entry = (Element) nodeList.item(i);
entry.normalize();
Element _titleE = (Element) entry.getElementsByTagName(
"title").item(0);
Element _categoryE = (Element) entry
.getElementsByTagName("category").item(0);
Element _pubDateE = (Element) entry
.getElementsByTagName("pubDate").item(0);
Element _linkE = (Element) entry.getElementsByTagName(
"link").item(0);
String _title = _titleE.getFirstChild().getNodeValue();
String _category = _categoryE.getFirstChild().getNodeValue();
Date _pubDate = new Date(_pubDateE.getFirstChild().getNodeValue());
String _link = _linkE.getFirstChild().getNodeValue();
//create RssItemObject and add it to the ArrayList
RssItem rssItem = new RssItem(_title, _category, _pubDate, _link);
rssItems.add(rssItem);
conn.disconnect();
}
Don't use getFirstElement when you really want getTextContent.

Categories