I have to extract tag value from an xml Document that contains a single tag like below:
<error>Permission denied</error>
i have tried:
String xmlRecords = "<error>Permission denied</error>"
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
Document doc = db.parse(is);
Node nodes = doc.getFirstChild();
String = nodes.getNodeValue();
but it dont works.
How can i do it ?
Use doc.getDocumentElement().getTextContent() to get the string Permission denied.
With DOM it´s util to know the structure of the XML document, and which node level are you looking for.
After get Document, you can use document.getElementsByTagName("root") to look for the root or father tags, and get the childs as a list to look for the item. Something like this:
NodeList listresults = document.getElementsByTagName('father/root element string');
NodeList nl = listresults.item(0).getChildNodes();
// Recorremos los nodos
for (int temp = 0; temp < nl.getLength(); temp++) {
Node node = nl.item(temp);
// Check if it is a node
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
if(element.getNodeName().equals("error")){
// check the element
}
}
}
I hope this helps you.
just try following code.
String value = nodes.getTextContent();
You have to construct the string if you are using the above approach. You will get the string values of the tag name and content using the functions.
Tag name = nodes.getTextContent()
tag value = nodes.getLocalName()
I guess this is what you want
Element element = document.getDocumentElement();
NodeList errorTagList = element.getElementsByTagName("error");
if (errorTagList != null && errorTagList.getLength() > 0) {
NodeList errorTagSubList = errorTagList.item(0).getChildNodes();
if (errorTagSubList != null && errorTagSubList.getLength() > 0) {
String value = errorTagSubList.item(0).getNodeValue();
}
}
Related
How do I list the element names at a given level in an xml schema hierarchy? The code I have below is listing all element names at every level of the hierarchy, with no concept of nesting.
Here is my xml file:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><?xml-stylesheet type="text/xsl" href="CDA.xsl"?>
<SomeDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="urn:something">
<title>some title</title>
<languageCode code="en-US"/>
<versionNumber value="1"/>
<recordTarget>
<someRole>
<id extension="998991"/>
<addr use="HP">
<streetAddressLine>1357 Amber Drive</streetAddressLine>
<city>Beaverton</city>
<state>OR</state>
<postalCode>97867</postalCode>
<country>US</country>
</addr>
<telecom value="tel:(816)276-6909" use="HP"/>
</someRole>
</recordTarget>
</SomeDocument>
Here is my java method for importing and iterating the xml file:
public static void parseFile() {
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
Document dom = db.parse("D:\\mypath\\somefile.xml");
//get the root element
Element docEle = dom.getDocumentElement();
//get a nodelist of elements
NodeList nl = docEle.getElementsByTagName("*");
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("node.getNodeName() is: "+node.getNodeName());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
The output of the above program is:
title
languageCode
versionNumber
recordTarget
someRole
id
addr
streetAddressLine
city
state
postalCode
country
telecom
Instead, I would like to output the following:
title
languageCode
versionNumber
recordTarget
It would be nice to then be able to list the children of recordTarget as someRole, and then to list the children of someRole as id, addr, and telecom. And so on, but at my discretion in the code. How can I change my code to get the output that I want?
You're getting all nodes with this line:
NodeList nl = docEle.getElementsByTagName("*");
Change it to
NodeList nl = docEle.getChildNodes();
to get all of its children. Your print statement will then give you the output you're looking for.
Then, when you iterate through your NodeList, you can choose to call the same method on each Node you create:
NodeList children = node.getChildNodes();
If you want to print an XML-like structure, perhaps a recursive method that prints all child nodes is what you are looking for.
You could re-write the parseFile (I'd rather call it parseChildrenElementNames) method to take an input String that specifies the element name for which you want to print out its children element names:
public static void parseChildrenElementNames(String parentElementName) {
// get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using builder to get DOM representation of the XML file
Document dom = db
.parse("D:\\mypath\\somefile.xml");
// get the root element
NodeList elementsByTagName = dom.getElementsByTagName(parentElementName);
if(elementsByTagName != null) {
Node parentElement = elementsByTagName.item(0);
// get a nodelist of elements
NodeList nl = parentElement.getChildNodes();
if (nl != null) {
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
System.out.println("node.getNodeName() is: "
+ node.getNodeName());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
However, this will only consider the first element that matches the specified name.
For example, to get the list of elements under the first node named someRole, you would call parseChildrenElementNames("someRole"); which would print out:
node.getNodeName() is: id
node.getNodeName() is: addr
node.getNodeName() is: telecom
I want to parse an XML file i exported from a database software, for my android app.
However some of the tags have arguments like so:
<row>
<value column="Index" null="false">1</value>
<value column="Front" null="false">INFO</value>
<value column="Back" null="false">INFO</value>
<value column="Check" null="false">0</value>
</row>
what string value do i specify while trying to find the start tag to parse it?
( for example: to find the row i compare the start tap to "row" and if it returns true i compute the data. What do i do for each value i.e Index,Front,Back and Check separately?)
My java code is as follows
try{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
InputStream stream = context.getResources().openRawResource(com.Whydea.chemistryhelper.R.raw.appxml);
xpp.setInput(stream, null);
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT){
if(eventType==XmlPullParser.START_TAG){
handleStartTag(xpp.getName()); //handels Start Tag
} else if (eventType==XmlPullParser.END_TAG){
handleEndTag(xpp.getName());
Ctag=null;
} else if (eventType==XmlPullParser.TEXT){
handleText(xpp.getText());
}
eventType=xpp.next();
}
}catch (NotFoundException e){
Log.d("XMLpp",e.getMessage());
}catch (XmlPullParserException e){
Log.d("XMLpp",e.getMessage());
}catch (IOException e){
Log.d("XMLpp",e.getMessage());
}
`
EDIT:
Each "value" start tags has its own attribute(column=...), how do i access those?
For example: to access a row, i have a String constant with the value "row", and check if the start tag corresponds to that, and it works. But when i declare a string constant with value "value column=\"Check\" null=\"false\""( i have to use \ other wise " give errors), it does not find find that start tag. So what should my constant be?
if i understand your question correctly then to get each of the values you need to do following, basically you want to get the value of each attribute inside the xml tag
int attributeCount = xpp.getAttributeCount();
for(int i = 0; i<attributeCount; i++){
String name = xpp.getAttributeName(i);
//Log.d(TAG, "Name: "+name);
if(name != null && name.equalsIgnoreCase("column")){
return Integer.parseInt(xpp.getAttributeValue(i));
}
}
So once you have encountered the row then you look for the start Tag "value" once you have found it, then use the above code to get the individual value of attributes.
As per your comment if you want to get the text value of an XML tag then you will have to use the getText() method. Once you have found the START_TAG value then execute below code:
eventType = xpp.next();
if(eventType == XmlPullParser.TEXT){
String text = xpp.getText();
}
For the xml tag 'INFO' value it will return 'INFO'
try {
final Service S = new Service();
String xmlString = S.ImportAllPollBoothStatus(IMEI,asscd, boothno);
if(xmlString.toLowerCase().trim().equals("false")){
return false;
}
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlString));
Document doc = docBuilder.parse(is);
NodeList nodes = doc.getElementsByTagName("HT");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList blockidnodes = doc.getElementsByTagName("Table");
for (int blockidcount = 0; blockidcount < blockidnodes
.getLength(); blockidcount++) {
NodeList PollpercentId = element
.getElementsByTagName("PollpercentId");
Element line1 = (Element) PollpercentId.item(blockidcount);
NodeList asscd1 = element
.getElementsByTagName("asscd");
Element line2 = (Element) asscd1.item(blockidcount);
NodeList pollgcd = element
.getElementsByTagName("pollgcd");
Element line3 = (Element) pollgcd.item(blockidcount);
NodeList SessionYearIdref = element
.getElementsByTagName("SessionYearIdref");
Element line4 = (Element) SessionYearIdref.item(blockidcount);
NodeList MaleVoters = element
.getElementsByTagName("MaleVoters");
Element line5 = (Element) MaleVoters.item(blockidcount);
NodeList FemaleVoters = element
.getElementsByTagName("FemaleVoters");
Element line6 = (Element) FemaleVoters.item(blockidcount);
NodeList UpdatedDate = element
.getElementsByTagName("UpdatedDate");
Element line7 = (Element) UpdatedDate.item(blockidcount);
NodeList timeslot = element
.getElementsByTagName("timeslot");
Element line8 = (Element) timeslot.item(blockidcount);
this.db.insertVotingStatus(
getCharacterDataFromElement(line1),
getCharacterDataFromElement(line2),
getCharacterDataFromElement(line3),
getCharacterDataFromElement(line4),
getCharacterDataFromElement(line5),
getCharacterDataFromElement(line6),
getCharacterDataFromElement(line7),
getCharacterDataFromElement(line8));
}
}
}
catch (Exception e) {
Log.e("EXCEPTION DURING VIDHANSABHA INSERION",
"======Insert-VIDHANSABHA-DETAILS=====================" + e);
return false;
}
return true;
Did you develop the app which generates the XML file? If so why don't you change it? It would be much easier to parse the XML if it has this format:
<item Index="1" Front="INFO" Back="INFO" Check="0"/>
<item Index="2" Front="INFO" Back="INFO" Check="1"/>
I am using DOM to parse an XML string as in the following example. This works great except in one instance. The document which I am trying to parse looks like this:
<response requestID=\"1234\">
<expectedValue>Alarm</expectedValue>
<recommendations>For steps on how to resolve visit Website and use the search features for \"Alarm\"<recommendations>
<setting>Active</setting>
<response>
The code I used to parse the XML is as follows:
try {
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlResult));
Document doc = db.parse(is);
NodeList nlResponse = doc.getElementsByTagName("response");
String[] String = new String[3]; //result entries
for (int i = 0; i < nlResponse.getLength(); i++) {
Element e = (Element) nlResponse.item(i);
int c1 = 0; //count for string array
NodeList ev = e.getElementsByTagName("expectedValue");
Element line = (Element) ev.item(0);
String[c1] = (getCharacterDataFromElement(line));
c1++;
NodeList rec = e.getElementsByTagName("recommendations");
line = (Element) rec.item(0);
String[c1] = (getCharacterDataFromElement(line));
c1++;
NodeList set = e.getElementsByTagName("settings");
line = (Element) set.item(0);
String[c1] = (getCharacterDataFromElement(line));
c1++;
I am able to parse the code and put the result into a string array (as opposed to the System.out.println()). With the current code, my string array looks as follows:
String[0] = "Alarm"
String[1] = "For steps on how to resolve visit"
String[2] = "Active"
I would like some way of being able to read the rest of the information within "Recommendations" in order to ultimately display the hyperlink (along with other output) in a TextView. How can I do this?
I apologize for my previous answer in assuming your xml was ill-formed.
I think what is happening is that your call to the getCharacterDataFromElement is only looking at the first child node for text, when it will need to look at all the child nodes and getting the href attribute as well as the text for the 2nd child node when looking at the recommendations node.
e.g. after getting the Element for recommendation
String srec = "";
NodeList nl = line.getChildNodes();
srec += nl.item(0).getTextContent();
Node n = nl.item(1);
NamedNodeMap nm = n.getAttributes();
srec += "" + n.getTextContent() + "";
srec += nl.item(2).getTextContent();
String[c1] = srec;
I am trying to write a piece of code that can parse any xml and print its contents. I am using DOM parser. I am able to get the name of the root tag of the xml, but cant obtain tag name of the immediate child. This can be done easily in case the node names are known by using the method 'getElementsByTagName' . Is there any way out of this dilemma ?
My code goes like this :
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
doc.getDocumentElement().getNodeName() // this gets me the name of the root node.
Now how can i get the name of the immediate child node so that i can traverse the xml using getElementsByTagName("x").
Thanks in advance.
getChildNodes() returns all children of an element. The list will contain more then just elements so you'll have to check each child node if it is an element:
NodeList nodes = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.get(i);
if (node instanceof Element) {
Element childElement = (Element) node;
System.out.println("tag name: " + childElement.getTagName());
}
}
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.