i have a xml file and i am parsing it with DOM. `
<media:group>
<media:category label='hi'scheme='http://gdata.youtube.com/schemas/2007/categories.cat'>hello</media:category>
<media:content
url='http://www.youtube.com/1'
expression='full' duration='37' yt:format='5' />
<media:content
url='rtsp://v8.cache8.c.youtube.com.2.gp'
type='video/3gpp' medium='video' expression='full' duration='37'
yt:format='1' />
</media:group>
(Not original links)
like this it has many media:group tag...
my code is giving bellow:
nodeList = doc.getElementsByTagName("media:group");
for (int i = 0; i < nodeList.getLength(); i++) {
try {
currentNode = nodeList.item(i);
Element fstElmnt = (Element) currentNode;
NodeList media_list = fstElmnt
.getElementsByTagName("media:content");
Element mediaElement = (Element) media_list.item(0);
media_list = mediaElement.getChildNodes();
String urlString = mediaElement.getAttribute("url");
Now my problem is this i want all url of all media:content tag,, but getting only 1st url of every media:content tag.
so where i am doing mistake please help me...
You only ask for the first media element in the list by using:
Element mediaElement = (Element) media_list.item(0);
Of course this will crash if the media list is empty. Solution to your problem: Just loop over media_list. ;-)
Your problem lies here (you're getting only the first item on media_list):
Element mediaElement = (Element) media_list.item(0);
In your sample ATOM there's 2 media:content elements. I would iterate through media_list and get the item(i) and do String urlString = mediaElement.getAttribute("url"); and add the urlString into a list. That way, you have all the url in a list.
Hope this helps.
Related
I'm trying to parse an XML file. The format of the XML file is:
<Testcase>
<Title>Low Load</Title>
<MO_Call>DIAL</MO_Call>
<Delay>10</Delay>
<MO_Call>HANGUP</MO_Call>
<Delay>10</Delay>
<MO_SMS>SEND</MO_SMS>
</Testcase>
I need to get the key-value pairs under the node "Testcase" and store in a datastructure. Ordering is important, and hence I'm considering a LinkedHashMap.
Please suggest the right way to get the key-value pairs from the XMl file.
In the above XML snippet, the corresponnding key-value pairs are:
Key: MO_Call, Value: DIAL
Key: Delay, Value: 10
I have written the below code for parsing the XML:
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new FileInputStream(CONFIG_PATH));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName(TAG_TEST_CASE);
if (nodeList != null && nodeList.getLength() > 0) {
for (int i=0; i < nodeList.getLength(); i++) {
Element el = (Element) nodeList.item(i);
// If title doesn't match, check the next title under next 'Testcase' NodeList
if(el.getFirstChild().getNodeName().equals(TAG_TITLE) &&
!el.getFirstChild().getNodeValue().equals(title)) {
continue;
}
// else, title matches. So parse the child nodes.
// Start from index 1, since index 0 is title always
NodeList childNodeList = el.getChildNodes();
for(int j=1; j < childNodeList.getLength(); j++) {
Node childNode = childNodeList.item(j);
//Element childElement = (Element) childNodeList.item(j);
Log.d("Tool", "key=" +childNode.getNodeName()+ ", value=" +childNode.getTextContent());
}
}
}
}
I'm getting the output:
key=Title, value=Low Load
key=#text, value=
key=MO_Call, value=DIAL
key=#text, value=
key=Delay, value=10
key=#text, value=
key=MO_Call, value=HANGUP
key=#text, value=
key=Delay, value=10
key=#text, value=
key=MO_SMS, value=SEND
key=#text, value=
key=Title, value=Medium Load
key=#text, value=
key=Title, value=High Load
key=#text, value=
For some reason, the key "#text" is coming up along with null value. Please help me avoid this.
Please, reffer here for the #text. If you can alter the XML, remove ALL spaces that are unintentional, then re-test your code.
Example XML:
<?xml version="1.0" encoding="UTF-8"?><Testcase><Title>Low Load</Title><MO_Call>DIAL</MO_Call><Delay>10</Delay><MO_Call>HANGUP</MO_Call><Delay>10</Delay><MO_SMS>SEND</MO_SMS></Testcase>
Also, please show the encode used on the XML file, there could be typos.
This is also a good suggestion on how to parse
Hi i want to parse this
<entry>
<id>http://306721</id>
<title type='text'>MY New</title>
<photo:id>513306721</gphoto:id>
<photo:name>MYNew</gphoto:name>
<photo:numphotos>9</gphoto:numphotos>
<media:group>
<media:content url='http:Ya4MIz9Y/MYNew.jpg' medium='image' type='image/jpeg' />
<media:keywords />
<media:thumbnail url='htt0-c/MYNew.jpg' height='160' width='160' />
<media:title type='plain'>MY New</media:title>
</media:group>
</entry>
i am able to parsing this file, and also able to read some values from the above xml document like this
Document doc = db.parse(is);
NodeList entries = doc.getElementsByTagName("entry");
for (int i = 0; i < entries.getLength(); i++) {
Element element = (Element) entries.item(i);
albumIds.add(getCharacterDataFromElement((Element) element
.getElementsByTagName("photo:id").item(0)));
}
in the above code i am reading gphoto:id like this i am reading photo:name and photo:numphotos.
Now i want to read url from the media:thumbnail those are available in the media:group.. Can any one help me on this how to read this.
Please see below link of my SO Question, it will solve your problem and if you have any query regarding that then tell me.
XML Parsing Using DOM Parser
Add those values in to object(using java pojo) and add that object into ArrayList
try to use Below Code. Hope it will help you.
Document doc = db.parse(is);
NodeList entries = doc.getElementsByTagName("entry");
for (int i = 0; i < entries.getLength(); i++) {
Element element = (Element) entries.item(i);
albumIds.add(getCharacterDataFromElement((Element) element
.getElementsByTagName("gphoto:id").item(0)));
NodeList nodelist_group = doc.getElementsByTagName("media:group");
for (int j = 0; j < nodelist_group.getLength(); j++) {
Element element = (Element) nodelist_group.item(j);
NodeList nodelist_content = doc.getElementsByTagName("media:content");
URLS.add(nodelist_content.getAttribute('url'))); }}
I have one XML which look like this ::
<Channels>
<Channel Id="511" Title="Test" ChannelDescription="This is Test Channel./>
</Channels>
I am successfully parse this kind of XML.My Problem is that when i fired the webservice and if there is no authentication from the server then the webservice response like this::
<AuthenticationError>An Active Session Already Exists For This User.</AuthenticationError>
So how can i check that root node is "Authentication Error" or "Notes". And if i get the Authentication Error tag then how can i get its node value which is "An Active Session Already Exists For This User."??
Code for XML Parsing is this::
NodeList node =null;
node= (NodeList)result.getElementsByTagName("Channels");
for(int j=0;j<node.getLength();j++)
{
Node aNode=node.item(j);
Element fstElmnt = (Element) aNode;
NodeList websiteList = fstElmnt.getElementsByTagName("Channel");
int check=websiteList.getLength();
for(int k=0;k<check;k++)
{
DatabaseConstant myChannels = new DatabaseConstant();
Node checkNode=websiteList.item(k);
Element websiteElement = (Element) checkNode;
myChannels.id=websiteElement.getAttribute("Id");
myChannels.title=websiteElement.getAttribute("Title");
channel .add(myChannels);
}
}
}
I hope my question is clear... Please provide the solution asap. Thanks in Advance....
Use getDocumentElement() to get root Element, then use getTagName() to get tag name.
Example:
Element root = result.getDocumentElement();
String name = root.getTagName();
if(name.equalsIgnoreCase("AuthenticationError") )
{
String value = myDocument.getDocumentElement().getTextContent();
System.out.println("Error:" + value);
}
else if(name.equalsIgnoreCase("Notes") )
{
NodeList nodes = root.getElementsByTagName("Channels");
for(int i = 0 ; i < nodes.getLength() ; i ++)
{
//-----do something with channels nodes--
}
}
I would like to list all the values of the tag inside in android 4.0 as of now I am able to get only one value I have added the snippet which I am using right now & also the xml below.Please help with the this with snippet or example.Thanks a lot.
NodeList nodes = doc.getElementsByTagName("month");
for (int i = 0; i < nodes.getLength(); i++)
{
Element e = (Element) nodes.item(i);
stock_list.add(getValue(e, "month"));
}
Here is my xml
The nodeValue of an XML Element is null by definition. Thus, you can either
query the element's children for the Text node containing the actual contents, or
simply use e.getTextContent() to retrieve the text content of the XML element.
Try this code i was having the same problem and solved it this way..
ArrayList<HashMap<String, String>> stock_list = new ArrayList<HashMap<String, String>>();
NodeList nodes = doc.getElementsByTagName("month");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Node name = nodes.item(i);
NodeList month = name.getChildNodes();
map.put("months", ((Node) month.item(0)).getNodeValue());
stock_list.add(map);
}
I have an xml that i am parsing through DOM parser. the xml is of somewhat this sequence
<root>
<item1> abc </item1>
<item2> def </item2>
<item3> ghi </item3>
<item4>
<subItem4>
<name> xyz </name>
<id> 1 </id>
</subItem4>
<subItem4>
<name> asd </name>
<id> 2 </id>
</subItem4>
</item4>
</root>
According to this dummy xml i am reaching till subItem 4 but not to the childern of it. what i am trying is as follows to get innermost Items is:
NodeList slide = theElement.getElementsByTagName("item4").item(0).getChildNodes();
for(int i = 0; i<slide.getLength(); i++)
{
NodeList subSlides = theElement.getElementsByTagName("subItem4").item(0).getChildNodes();
for (int j=0; j<subSlides.getLength(); j++)
{
String subSlide_title = subSlides.item(i).getFirstChild().getNodeValue();
}
}
its not working. please can someone identify where am i doing the mistake in parsing. Any help is appreciated.
You are not using valid XML - you can't have spaces in tag names.
XML Names cannot contain white space, see here for valid values.
Update (following comment that the posted sample is representative of the actual XML):
Your access via the indexer of the node list is incorrect:
String subSlide_title = subSlides.item(i).getFirstChild().getNodeValue();
Try this instead (using j instead of i, as the inner loop variable is called):
String subSlide_title = subSlides.item(j).getFirstChild().getNodeValue();
NodeList nodes = doc.getElementsByTagName("item");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList nodesimg = element.getElementsByTagName("name");
for (int j = 0; j < nodesimg.getLength(); j++) {
Element line = (Element) nodesimg.item(j);
String value=getCharacterDataFromElement(line);
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
I think above code will help you in parsing xml file.
The XML elements are all messed up.
There are literally 2 lines that don't have mistakes in them.
For instance
<subItem 4>
is syntactically wrong and I don't see what logical sense you could make out of it.
Do you mean
<subItem4>
as in the fourth sub item or
<subItem someAttribute="4">
I'd recommend learning XML, it's very simple... http://www.w3schools.com/xml/default.asp