parsing xmll file through java - java

I am using SAXParse in java to parse an xml file. I was successfully able to do this with one of the files but I moved to second file and tried reading an attribute I kept getting null. I have thought of every possible cause I can but I am not able to figure it out.
Here's a sample of xml file:
<?xml version="1.0" encoding="UTF-8"?>
<ProcessorStatusCode/>
<StatusCode>E</StatusCode>
<ErrorNo>1852</ErrorNo>...
And here's my java code:
public class ReadXML
{
public static void main(String[] args) throws IOException,SAXException, ParserConfigurationeException
{
String OrderNum;
SAXParserFactory parser = SAXParserFactory.newInstance();
SAXParser Sparser = parser.newSAXParser();
ReadXML handler = new ReadXML();
Sparser.parse("ErrorDescription.xml",handler);
}
public void characters(char[] buffer,int start,int length)
{
temp = new String(buffer, start, length);
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
temp = " ";
if(qName.equalsIgnoreCase("ErrorNo"))
{
//transaction = new Transaction();
OrderNum = attributes.getValue(ErrorNo);
}
}
public void endElement(String uri, String localName, String qName) throws SAXException
{
if(qName.equalsIgnoreCase("ErrorNo"))
{
System.out.println(OrderNum);
}
}
}//end of class

String OrderNum is declared as a local variable in the main() method, it should be a class member variable instead to be accessible in ReadXML.startElement().

Related

Updating XML File using SAX Parser

I try to update XML file which was read from the database, saved as a XMLType and then i performed SAXParse saving in variables all information i needed to use to construct further queries to the database. Basing on the values I've read I'm checking some conditions and then I want to update values of 3 nodes. How can I update the values. Below is the code I use to parse document but I have no idea how to update XML file in java using SAX.
public void parseXML(int i) throws XMLParseException, SAXException, IOException, SQLException {
String xml = printXML(i);
saxParser.parse(new InputSource(new StringReader(xml)), handler);
}
And in handler i have various conditions to save things I'm interested in like:
public class UserHandler extends DefaultHandler {
StringBuilder builder = new StringBuilder();
private Data data = new Data();
boolean idOrder = false;
boolean idReader = false;
#Override
public void startElement(String uri,
String localName, String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("order")) {
data.setIdOrder(attributes.getValue("ID_ORDER"));
} else if (qName.equalsIgnoreCase("id_reader")) {
idReader = true;
}
builder.setLength(0);
}
#Override
public void endElement(String uri,
String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("id_reader")) {
data.setIdReader(builder.toString());
}
}
#Override
public void characters(char ch[],
int start, int length) throws SAXException {
if (idReader) {
builder.append(new String(ch, start, length));
}
}
}
Please give me some hints.

Java XML Parsing using SAXParser

I have an API.When we request it will produce XML as response data
The below is the API Response for Description field:
<parameter>
<name>description</name>
<value>Description Description</value>
</parameter>
The below is the code to parse XML File(SAXPraser)
public class WorkOrderDataHandler extends DefaultHandler {
public WorkOrderDataHandler() {
parameterList = new ArrayList<Parameter>();
contentsOfTheCurrentTag = new StringBuilder();
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("Details")) {
ticketData = new TicketInterMediateData();
}
if (qName.equalsIgnoreCase("parameter")) {
parameter = new Parameter();
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
int length = contentsOfTheCurrentTag.length();
if (qName.equalsIgnoreCase("name")) {
parameter.setName(contentsOfTheCurrentTag.toString().trim());
}
if (qName.equalsIgnoreCase("value")) {
parameter.setValue(contentsOfTheCurrentTag.toString().trim());
}
if (qName.equalsIgnoreCase("parameter")) {
parameterList.add(parameter);
}
if (qName.equalsIgnoreCase("parameter")) {
if ("workorderid".equals(parameter.getName())) {
ticketData.setIt360ticketid(Integer.parseInt(parameter
.getValue().trim()));
}
else if ("description".equals(parameter.getName())) {
System.out.println("Handler desc"+ parameter.getValue());//DescriptionDescriptionÂ
ticketData.setDescription((parameter.getValue()));
}
}
contentsOfTheCurrentTag.delete(0, length);
}
public void characters(char ch[], int start, int length)
throws SAXException {
contentsOfTheCurrentTag.append(ch, start, length);
}
}
Output:
When i tried to parse the description field. i am getting the output as DescriptionDescriptionÂ
Could anyone please help

Java SAX is not parsing properly

I would appreciate any help on this.
This is my first handler I wrote.
I got I REST Webservice returning XML of links. It has quite simple structure and is not deep.
I wrote a handler for this:
public class SAXHandlerLnk extends DefaultHandler {
public List<Link> lnkList = new ArrayList();
Link lnk = null;
private StringBuilder content = new StringBuilder();
#Override
//Triggered when the start of tag is found.
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals("link")) {
lnk = new Link();
}
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("link")) {
lnkList.add(lnk);
}
else if (qName.equals("applicationCode")) {
lnk.applicationCode = content.toString();
}
else if (qName.equals("moduleCode")) {
lnk.moduleCode = content.toString();
}
else if (qName.equals("linkCode")) {
lnk.linkCode = content.toString();
}
else if (qName.equals("languageCode")) {
lnk.languageCode = content.toString();
}
else if (qName.equals("value")) {
lnk.value = content.toString();
}
else if (qName.equals("illustrationUrl")) {
lnk.illustrationUrl = content.toString();
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
content.append(ch, start, length);
}
}
Some XML returned can be empty eg. or . When this happens my handler unfortunatelly adds previous value to the Object lnk. So when is empty in XML, I got lnk.illustrationUrl = content; equal to lnk.value.
Link{applicationCode='onedownload', moduleCode='onedownload',...}
In the above example, I would like moduleCode to be empty or null, because in XML it is an empty tag.
Here is the calling class:
public class XMLRepositoryRestLinksFilterSAXParser {
public static void main(String[] args) throws Exception {
SAXParserFactory parserFactor = SAXParserFactory.newInstance();
SAXParser parser = parserFactor.newSAXParser();
SAXHandlerLnk handler = new SAXHandlerLnk();
parser.parse({URL}, handler);
for ( Link lnk : handler.lnkList){
System.out.println(lnk);
}
}
}
Like stated in my comment, you'd do the following. The callbacks are usually called in startElement, characters, (nested?), characters, endElement order, where (nested?) represents an optional repeat of the entire sequence.
#Override
//Triggered when the start of tag is found.
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
content = null;
if (qName.equals("link")) {
lnk = new Link();
}
}
Note that characters may be called multiple times per a single XML element in your document, so your current code might fail to capture all content. You'd be better off using a StringBuilder instead of a String object to hold your character content and append to it. See this answer for an example.

Sax parser issues in android

I'm trying to parse a xml using SAX parser. The code works fine on pc but on android the elements doesn't get added to list .
In the code i'm trying to add the data within the tags sunrise & sunset onto the list array
In public
void endElement(..) {}
System.out.println("size of list " + timeLst.size()); //Always shows 0 in android
Below is the code..
TimeServiceParser tsp = new TimeServiceParser();
tsp.parseDocument(new URL("http://www.earthtools.org/sun/47.566667/-52.716667/14/3/99/1"));
tsp.printData();
public class TimeService extends DefaultHandler {
public void parseDocument(URL sourceUrl) {
SAXParserFactory spf = SAXParserFactory.newInstance();
try{
SAXParser sp = spf.newSAXParser();
InputStream is = sourceUrl.openStream();
sp.parse(is, this);
}catch(SAXException se) {
...
}
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
tempVal = "";
if(qName.equalsIgnoreCase("sunrise")) {
tempTimeData = new TimeData();
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("sunrise")) {
tempTimeData.setSunriseTime(tempVal);
timeLst.add(tempTimeData);
}else if(qName.equalsIgnoreCase("sunset")) {
if(tempTimeData!=null) {
TimeData t = (TimeData)(timeLst.get(0));
t.setSunsetTime(tempVal);
}
}
System.out.println("size of list " + timeLst.size()); //Always shows 0 in android
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch , start , length);
}
public void printData() {
Iterator<TimeData> it = timeLst.listIterator();
while(it.hasNext()) {
TimeData td = (TimeData)(it.next());
System.out.println(td.getSunriseTime());
System.out.println(td.getSunsetTime());
}
}
}

Reading nested tags with sax parser

i am trying to read a xml file with following tag, but the sax parser is unable to read nested tags like
<active-prod-ownership>
<ActiveProdOwnership>
<Product code="3N3" component="TRI_SCORE" orderNumber="1-77305469" />
</ActiveProdOwnership>
</active-prod-ownership>
here is the code i am using
public class LoginConsumerResponseParser extends DefaultHandler {
// ===========================================================
// Fields
// ===========================================================
static String str="default";
private boolean in_errorCode=false;
private boolean in_Ack=false;
private boolean in_activeProdOwnership= false;
private boolean in_consumerId= false;
private boolean in_consumerAccToken=false;
public void startDocument() throws SAXException {
Log.e("i am ","in start document");
}
public void endDocument() throws SAXException {
// Nothing to do
Log.e("doc read", " ends here");
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if(localName.equals("ack")){
in_Ack=true;
}
if(localName.equals("error-code")){
in_errorCode=true;
}
if(localName.equals("active-prod-ownership")){
Log.e("in", "active product ownership");
in_activeProdOwnership=true;
}
if(localName.equals("consumer-id")){
in_consumerId= true;
}
if(localName.equals("consumer-access-token"))
{
in_consumerAccToken= true;
}
}
/** Gets be called on closing tags like:
* </tag> */
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if(localName.equals("ack")){
in_Ack=false;
}
if(localName.equals("error-code")){
in_errorCode=false;
}
if(localName.equals("active-prod-ownership")){
in_activeProdOwnership=false;
}
if(localName.equals("consumer-id")){
in_consumerId= false;
}
if(localName.equals("consumer-access-token"))
{
in_consumerAccToken= false;
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
public void characters(char ch[], int start, int length) {
if(in_Ack){
str= new String(ch,start,length);
}
if(str.equalsIgnoreCase("success")){
if(in_consumerId){
}
if(in_consumerAccToken){
}
if(in_activeProdOwnership){
str= new String(ch,start,length);
Log.e("active prod",str);
}
}
}
}
but on reaching the tag in_activeProdOwnersip read only "<" as the contents of the tag
please help i need to the whole data to be read
The tags in your XML file and parser does not match. I think you are mixing-up tags with attribute names. Here is the code that correctly parses your sample XML:
public class LoginConsumerResponseParser extends DefaultHandler {
public void startDocument() throws SAXException {
System.out.println("startDocument()");
}
public void endDocument() throws SAXException {
System.out.println("endDocument()");
}
public void startElement(String namespaceURI, String localName,
String qName, Attributes attrs)
throws SAXException {
if (qName.equals("ActiveProdOwnership")) {
inActiveProdOwnership = true;
} else if (qName.equals("Product")) {
if (!inActiveProdOwnership) {
throw new SAXException("Product tag not expected here.");
}
int length = attrs.getLength();
for (int i=0; i<length; i++) {
String name = attrs.getQName(i);
System.out.print(name + ": ");
String value = attrs.getValue(i);
System.out.println(value);
}
}
}
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("ActiveProdOwnership"))
inActiveProdOwnership = false;
}
public void characters(char ch[], int start, int length) {
}
public static void main(String args[]) throws Exception {
String xmlFile = args[0];
File file = new File(xmlFile);
if (file.exists()) {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
DefaultHandler handler = new Test();
parser.parse(xmlFile, handler);
}
else {
System.out.println("File not found!");
}
}
private boolean inActiveProdOwnership = false;
}
A sample run will produce the following output:
startDocument()
code: 3N3
component: TRI_SCORE
orderNumber: 1-77305469
endDocument()
I suspect this is what's going wrong:
new String(ch,start,length);
Here, you're passing a char[] to the String constructor, but the constructor is supposed to take a byte[]. The end result is you get a mangled String.
I suggest instead that you make the str field a StringBuilder, not a String, and then use this:
builder.append(ch,start,length);
You then need to clear the StringBuilder each time startElement() is called.

Categories