You need to sign in to do that
Don't have an account?
Getting null in XMLStreamReader while reading attribute
public void parseXML(XmlStreamReader xsr)
{
while(xsr.hasNext())
{
if (xsr.getEventType() == XmlTag.START_ELEMENT)
{
if ('body' == xsr.getLocalName())
{
m_xmlValue += '-' + ' ' + parseRoot(xsr);
// parseRoot(xsr);
}
}
xsr.next();
}
}
public String parseRoot(XmlStreamReader xsr)
{
String value ='';
value += '---> ' + xsr.getAttributeValue('', 'chapter');
System.debug('The value of chapter is ::'+value);
while(xsr.hasNext())
{
if (xsr.getEventType() == XmlTag.END_ELEMENT)
{
break;
}
else if (xsr.getEventType() == XmlTag.CHARACTERS)
{
value += xsr.getText();
}
xsr.next();
}
return value;
}
public TestGoogleAppController()
{
try
{
//TestGoogleAppController tstGoogleApp = new TestGoogleAppController();
m_xmlValue = '';
//Playing with XML
//String xml = '<root><body chapter="1">Hello Peace</body><body chapter="2">Sumiran</body><body chapter="3">How</body></root>';
String xml = '<body chapter="1">Hello Peace</body>';
XmlStreamReader xsr = new XmlStreamReader(xml);
parseXML(xsr);
}
}
Guys, I have been stuck on this problem since morning.So please help out.
I am try to read the xml.I can read the values present between tags but I get "null" while reading attributes.Please could you point me in the right direction
I also followed the apex developer's guide using 'value += '---> ' + xsr.getAttributeValue('', 'chapter');', but it only returns null. Then I found out a better approach by loop through the start tags, try to find out all attributs' values in that tag:
for (Integer i = 0; i < reader.getAttributeCount(); i ++) { if (reader.getAttributeLocalName(i).equals('chapter')) { value = reader.getAttributeValueAt(i); } else if (reader.getAttributeLocalName(i).equals('XXX')) { put your logic here. } }
In this way, you will get the attribute's value instead of null.
All Answers
I also followed the apex developer's guide using 'value += '---> ' + xsr.getAttributeValue('', 'chapter');', but it only returns null. Then I found out a better approach by loop through the start tags, try to find out all attributs' values in that tag:
for (Integer i = 0; i < reader.getAttributeCount(); i ++) { if (reader.getAttributeLocalName(i).equals('chapter')) { value = reader.getAttributeValueAt(i); } else if (reader.getAttributeLocalName(i).equals('XXX')) { put your logic here. } }
In this way, you will get the attribute's value instead of null.
fwiw, I found the correct answer in this post: here
Pass null instead of '' for the first parameter ( reader.getAttributeValue(null,'author'); )
SalesForce Admins & Documentation guys: It would be _nice_ if you fixed the example in the Apex Reference for the XmlStreamReader class!
Thanks,
Rich C.
@Conejo, reader.getAttributeValue(null,'author'); is the correct answer. Thanks a lot for this, it really saved a lot of time
Thanks for posting this solution it was driving me nuts. Salesforce should really update their documentation...