I have the following xml format and wanted to read the elements in java . 'm very new to xml parsing.
<string xmlns="http://tempuri.org/">
<IDV><exshowroomPrice>48800</exshowroomPrice><idv_amount>46360</idv_amount><idv_amount_min>39406</idv_amount_min><idv_amount_max>53314</idv_amount_max><exshowroomPrice_min>41480</exshowroomPrice_min><exshowroomPrice_max>56120</exshowroomPrice_max><outputmessage></outputmessage></IDV>
<string>
I have added this and after that unable to extract the elements.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(responsebuffer.toString()));
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
System.out.println(doc.getDocumentElement().getTextContent());
NodeList nodes = doc.getChildNodes();
Node no1 = (Node) nodes.item(0);
if (doc.getDocumentElement().getChildNodes().getLength() > 0) {
if (nodes.item(0).getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) nodes.item(0);
NodeList nl =element.getElementsByTagName("exshowroomPrice");
System.out.println(((Node)nl).getNodeValue());
}
}
o/p:<IDV><exshowroomPrice>48800</exshowroomPrice><idv_amount>46360</idv_amount><idv_amount_min>39406</idv_amount_min><idv_amount_max>53314</idv_amount_max><exshowroomPrice_min>41480</exshowroomPrice_min><exshowroomPrice_max>56120</exshowroomPrice_max><outputmessage></outputmessage></IDV>
Kindly help,
Thanks in advance.
I'm not sure I understand your question, but your XML is malformed (it should end with ).
That said, the code to parse your document is correct, now I think the simplest way to extract individual elements would be to use class XPathAPI.
For instance:
Node node = XPathAPI.selectSingleNode(doc, "//string/IDV/exshowroomPrice");
System.out.println(node.getTextContent());
UPDATE:
Actually, XPathAPI is not a standard, but you can use XPath:
XPath xpath = XPathFactory.newInstance().newXPath();
String val = (String) xpath.evaluate("//string/IDV/exshowroomPrice/text()", doc, XPathConstants.STRING);
System.out.println(val);
Finally got the answer.
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(responsebuffer.toString()));
Document document = db.parse(is);
document.getDocumentElement().normalize();
//System.out.println(document.getDocumentElement().getTextContent());
StringBuilder xmlStringBuilder = new StringBuilder();
xmlStringBuilder.append("<?xml version=\"1.0\"?>");
xmlStringBuilder.append(document.getDocumentElement().getTextContent());
ByteArrayInputStream input = new ByteArrayInputStream(xmlStringBuilder.toString().getBytes("UTF-8"));
Document doc = db.parse(input);
NodeList nList = doc.getElementsByTagName("IDV");
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(eElement.getElementsByTagName("exshowroomPrice").item(0).getTextContent());
System.out.println(eElement.getElementsByTagName("idv_amount").item(0).getTextContent());
System.out.println(eElement.getElementsByTagName("idv_amount_min").item(0).getTextContent());
System.out.println(eElement.getElementsByTagName("idv_amount_max").item(0).getTextContent());
System.out.println(eElement.getElementsByTagName("exshowroomPrice_min").item(0).getTextContent());
System.out.println(eElement.getElementsByTagName("exshowroomPrice_max").item(0).getTextContent());
System.out.println(eElement.getElementsByTagName("outputmessage").item(0).getTextContent());
}
}
//getElementsByTagName("exshowroomPrice")
} catch (Exception e) {
e.printStackTrace();
}
Related
I want to parse an XML. I am posting my XML response below. In the
pre tag I am getting a JSON which i want to print but I am not able to parse with my code. I am posting my code to parse this XML.
private void xmlParsing(String qrCode) {
try {
qrCode = qrCode.replaceAll("[^\\x20-\\x7e]", "");
//loge("qrCode : " + qrCode);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ByteArrayInputStream(qrCode.getBytes("utf-8")));
Element element = doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("head");
loge("--df--nList.getLength()---"+nList.getLength());
for (int i=0; i<nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
<head></head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">{"status":true,"message":"Login Successfull","data":{"user":{"id":2,"name":"Rommy Garg","email":"rommy#signitysolutions.com","user_group_id":"2","company_id":2,"last_login":"2019-05-29 05:48:27","last_logout":"2019-05-28 10:33:39","profile_pic":null,"created_at":"2018-12-20 10:12:23","updated_at":"2019-05-29 05:48:27","sf_reference_id":"0056F00000BqMZSQA3","sf_setup":1},"company_logo":"http:\/\/staging.sales-chap.com\/dist\/uploads\/company\/1545300743.jpg","client_id":1,"client_secret":"IQ09J2BdDuc3lSKUJlQAp8uhCXRq+s2EucsBOb9rfjo="}}</pre>
</body>
but I am getting below error:
org.w3c.dom.DOMException: Only one root element allowed
Well, as the error said, XML only allows a single root element. You could create a fake one around the string you recieve:
qrCode = "<html>" + qrCode + "</html>";
I have the following XML (provided by a web service)
<?xml version="1.0" encoding="UTF-8"?>
<itam>
<status>OK</status>
<data>
<item0>
<id>246</id>
<prefisso_quadrato>1</prefisso_quadrato>
<id_incontro_corrente />
<id_giornata>65</id_giornata>
<round>R1</round>
<tempo>120</tempo>
<punti_chong>0</punti_chong>
<punti_hong>0</punti_hong>
<amm_chong>0</amm_chong>
<amm_hong>0</amm_hong>
</item0>
<item1>
<id>247</id>
<prefisso_quadrato>2</prefisso_quadrato>
<id_incontro_corrente />
<id_giornata>65</id_giornata>
<round>R1</round>
<tempo>120</tempo>
<punti_chong>0</punti_chong>
<punti_hong>0</punti_hong>
<amm_chong>0</amm_chong>
<amm_hong>0</amm_hong>
</item1>
<item2>
<id>248</id>
<prefisso_quadrato>3</prefisso_quadrato>
<id_incontro_corrente />
<id_giornata>65</id_giornata>
<round>R1</round>
<tempo>120</tempo>
<punti_chong>0</punti_chong>
<punti_hong>0</punti_hong>
<amm_chong>0</amm_chong>
<amm_hong>0</amm_hong>
</item2>
</data>
</itam>
I am trying to parse it in JAVA. I can access to the <status> and also to the <data> element. But when I try to iterate over <data> items, I can read just 1 element. This is the code:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
doc.getDocumentElement().normalize();
System.out.println(doc.getDocumentElement().getElementsByTagName("data").getLength());
OUTPUT: 1
My idea was something like the code below, but it runs just over the first element (I can read the rest element attributes and then it ends). How can I fix it? Thank you very much
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
doc.getDocumentElement().normalize();
NodeList nodelist = doc.getDocumentElement().getElementsByTagName("data");
if(nodelist!=null){
for(int i=0; i<nodelist.getLength(); i++){
Element el = (Element) nodelist.item(i);
//use el to get data from it
}
}
The error is that you are looking for a list of <data> element and you have just one. A solution can be:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
doc.getDocumentElement().normalize();
NodeList items = doc.getDocumentElement().getElementsByTagName("data").item(0).getChildNodes();
for(int i=0; i<items.getLength(); i++){
System.out.println(items.item(i).getNodeName());
}
Good luck!
You will have to recurively iterate over the xml file to get all the elements..
something like this
private Document getDocument(String xsdUrl)
throws ParserConfigurationException, SAXException, IOException {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
final DocumentBuilder db = dbf.newDocumentBuilder();
final Document doc = db.parse(xsdUrl);
return doc;
}
private void processElementRecurse(final Element node) throws IOException,
ParserConfigurationException, SAXException, TransformerException {
final NodeList nl = node.getChildNodes();
for (int i = 0, n = nl.getLength(); i < n; i++) {
final Node childNode = nl.item(i);
if (childNode instanceof Element) {
}
else {
processElementRecurse(childElement);
}
}
}
I have an android project with file res/raw/lvl.xml
<?xml version="1.0" encoding="utf-8"?>
<Level>
<dimensions>
<a>5</a>
<b>5</b>
</dimensions>
.
.
.
</Level>
My java code is following
InputStream input = this.getResources().openRawResource(R.raw.lvl);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = buider.parse(input);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("dimensions");
Node node = nList.item(0);
int a = Integer.parseInt(node.getFirstChild().getNodeValue().trim());
The last line throws parsing exception, node.getNodeValue().trim() is "\t\t\n\t".
You're looking at the <dimensions> tag, not at a and b. Look:
NodeList nList = doc.getElementsByTagName("dimensions");
Node node = nList.item(0);
int a = Integer.parseInt(node.getNodeValue().trim());
You're getting the first (index 0) element of name dimensions. Not its children.
The value you see (\t\t\n\t) is what's left of dimensions' contents after children nodes are removed.
Could not understand what exactly you are trying to do ...but .. you can refer below if that helps
public class Parsing {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
Parsing parse = new Parsing();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new File("x.xml"));
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("dimensions");
Node node = nList.item(0);
for (Node childNode = node.getFirstChild();
childNode != null;) {
//do something
System.out.println(childNode.getNodeName());
System.out.println(childNode.getTextContent());
Node nextChild = childNode.getNextSibling();
childNode = nextChild;
}
}
}
<person>
<firstname>
<lastname>
<salary>
</person>
This is the XML I am parsing. When I try printing the node names of child elements of person,
I get
text
firstname
text
lastname
text
salary
How do I eliminate #text being generated?
Update -
Here is my code
try {
NodeList nl = null;
int l, i = 0;
File fXmlFile = new File("file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
dbFactory.setValidating(false);
dbFactory.setIgnoringElementContentWhitespace(true);
dbFactory.setNamespaceAware(true);
dbFactory.setIgnoringComments(true);
dbFactory.setCoalescing(true);
InputStream in;
in = new FileInputStream(fXmlFile);
Document doc = dBuilder.parse(in);
doc.getDocumentElement().normalize();
Node n = doc.getDocumentElement();
System.out.println(dbFactory.isIgnoringElementContentWhitespace());
System.out.println(n);
if (n != null && n.hasChildNodes()) {
nl = n.getChildNodes();
for (i = 0; i < nl.getLength(); i++) {
System.out.println(nl.item(i).getNodeName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
setIgnoringElementContentWhitespace only works if you use setValidating(true), and then only if the XML file you are parsing references a DTD that the parser can use to work out which whitespace-only text nodes are actually ignorable. If your document doesn't have a DTD it errs on the safe side and assumes that no text nodes can be ignored, so you'll have to write your own code to ignore them as you traverse the child nodes.
i have been traipsing the internet for days and i really need some help, i am trying to parse in an XML document from a web server into a ListView in android, i have worked out how to do it with a local file and that is fine, but no matter what i find whether on stack or other sites it just doesnt seem to work, can anyone help me with this?? i know the page exists and works...ive pulled all my hair out now so pleas help :)
below is my code for the method, this is called after the on create and an onclicklistener for items,also i am using the document builder factory method.
private void xmlparse()
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(new URL("URL in here").openConnection().getInputStream());
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("item");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
titles.add(getTagValue(TITLE_1, eElement)); //TITLE_1 is the xml tag title
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
Am i missing something daft or have i missed the ball completely? can anyone point me to infomation which would help or just let me know :)
Cheers!!
I've made which do that task, you should do this following :
//Formattage des strings pour le passage en URL
from = URLEncoder.encode(from, "UTF-8");
to = URLEncoder.encode(to, "UTF-8");
String addressToConnect = "http://maps.googleapis.com/maps/api/distancematrix/xml?origins="+from+"&destinations="+to+"&mode=driving&units="+unit+"&sensor=false";
//Partie connexion
URL url = new URL(addressToConnect);
HttpURLConnection connexion = (HttpURLConnection) url.openConnection();
connexion.connect();
InputSource geocoderResultInputSource;
geocoderResultInputSource = new InputSource(connexion.getInputStream());
//Partie XML/XPATH
Document geocoderResultDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(geocoderResultInputSource);
XPath xpath = XPathFactory.newInstance().newXPath();
//On s'assure que la requete envoy�e � l'API � bien renvoy�e un STATUS = OK cf. Google API
NodeList nodeListCodeResult = (NodeList) xpath.evaluate("//status", geocoderResultDocument, XPathConstants.NODESET);
etc...
Hope it helps,