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.
Related
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.
I'm using SAX parser to parse XML and is working fine.
I have below tag in XML.
<value>•CERTASS >> Certass</value>
Here I expect '•CERTASS >> Certass' as output. but below code returns only Certass. Is there any issue with the special chars of value tag?
public void characters(char[] buffer, int start, int length) {
temp = new String(buffer, start, length);
}
It is not guaranteed that the characters() method will run only once inside an element.
If you are storing the content in a String, and the characters() method happens to run twice, you will only get the content from the second run. The second time that the characters method runs it will overwrite the contents of your temp variable that was stored from the first time.
To remedy this, use a StringBuilder and append() the contents in characters() and then process the contents in endElement(). For example:
DefaultHandler handler = new DefaultHandler() {
private StringBuilder stringBuilder;
#Override
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
stringBuilder = new StringBuilder();
}
public void characters(char[] buffer, int start, int length) {
stringBuilder.append(new String(buffer, start, length));
}
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println(stringBuilder.toString());
}
};
Parsing the String "<value>•CERTASS >> Certass</value>" and the handler above gives the output:
?CERTASS >> Certass
I hope this helps.
I ran into this problem the other day, it turns out the reason for this is the CHaracters method is being called multiple times in case any of these Characters are contained in the Value:
" "
' '
< <
> >
& &
Also be careful about Linebreaks / newlines within the value!!!
If the xml is linewrapped without your controll the characters method wil also be called for each line that is in the statement, plus it will return the linebreak! (which you manually need to strip out in turn).
A sample Handler taking care of all these problems is this one:
DefaultHandler handler = new DefaultHandler() {
private boolean isInANameTag = false;
private String localname;
private StringBuilder elementContent;
#Override
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
if (qname.equalsIgnoreCase("myfield")) {
isInMyTag = true;
this.localname = localname;
this.elementContent = new StringBuilder();
}
}
public void characters(char[] buffer, int start, int length) {
if (isInMyTag) {
String content = new String(ch, start, length);
if (StringUtils.equals(content.substring(0, 1), "\n")) {
// remove leading newline
elementContent.append(content.substring(1));
} else {
elementContent.append(content);
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qname.equalsIgnoreCase("myfield")) {
isInMyTag = false;
// do something with elementContent.toString());
System.out.println(elementContent.toString());
this.localname = "";
}
}
}
I'm trying to parse an XML containing geographic nodes and ways connecting the nodes using SAX parser. I store the parsed nodes in an ArrayMap<Long, MapPos> and the ways in an ArrayList<ArrayList<MapPos>>. When parsing a way, I create an ArrayList<MapPos> of the referenced nodes and add this to the ArrayList of ways.
After debugging the application, I see that startElement() and endElement() successfully adds the ways to the ArrayList, but in the endDocument() method the ways ArrayList contains nothing but a bunch of empty ArrayList.
Here is the java class:
public class ParkingDataExtractor {
private static List<ArrayList<MapPos>> roads = new ArrayList<ArrayList<MapPos>>();
public static List<ArrayList<MapPos>> getWaysFromXML()
throws ParserConfigurationException, SAXException, IOException{
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
DefaultHandler handler = new DefaultHandler() {
ArrayMap<Long, MapPos> nodes = new ArrayMap<Long, MapPos>();
ArrayList<MapPos> nodeBuffer = new ArrayList<MapPos>();
List<ArrayList<MapPos>> ways = new ArrayList<ArrayList<MapPos>>();
// private int i; // for debug purposes
#Override
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("node")) {
Long id = Long.parseLong(attributes.getValue("id"));
Float lat = Float
.parseFloat(attributes.getValue("lat"));
Float lon = Float
.parseFloat(attributes.getValue("lon"));
nodes.put(id, new MapPos(lat, lon));
} else if (qName.equalsIgnoreCase("nd")) {
Long ref = Long.parseLong(attributes.getValue("ref"));
nodeBuffer.add(nodes.get(ref));
}
}
#Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
if (qName.equalsIgnoreCase("way")) {
ways.add(nodeBuffer);
// i++;
// if(i==1590) // last element
// ArrayList<MapPos> test = ways.get(i-1); // test = [MapPos [x=..., y=..., z=0.0], MapPos [x=..., y=..., z=0.0],...]
nodeBuffer.clear();
}
}
#Override
public void endDocument() throws SAXException {
// ArrayList<MapPos> test = ways.get(i-1); // test = []
roads = ways;
}
};
saxParser.parse("file://" + Environment.getExternalStorageDirectory()
+ "/roadmap.xml", handler);
return roads;
}
}
When you call nodeBuffer.clear() you empty the list that you have just passed on to ways. You basically use the same nodeBuffer object over and over, and fill the ways list with a lot of references to the same object - which you empty each time.
The way you should do it is create a new ArrayList object using new and assign it to nodeBuffer every time. You will then have separate objects, each containing the list of nodes parsed in the latest round.
Try this way,hope this will help you to solve your problem.
public class ParkingDataExtractor {
private static List<ArrayList<MapPos>> roads = new ArrayList<ArrayList<MapPos>>();
public static List<ArrayList<MapPos>> getWaysFromXML() throws ParserConfigurationException, SAXException, IOException{
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
DefaultHandler handler = new DefaultHandler() {
ArrayMap<Long, MapPos> nodes = new ArrayMap<Long, MapPos>();
ArrayList<MapPos> nodeBuffer;
List<ArrayList<MapPos>> ways = new ArrayList<ArrayList<MapPos>>();
#Override
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("node")) {
Long id = Long.parseLong(attributes.getValue("id"));
Float lat = Float.parseFloat(attributes.getValue("lat"));
Float lon = Float.parseFloat(attributes.getValue("lon"));
nodes.put(id, new MapPos(lat, lon));
} else if (qName.equalsIgnoreCase("nd")) {
Long ref = Long.parseLong(attributes.getValue("ref"));
nodeBuffer = new ArrayList<MapPos>();
nodeBuffer.add(nodes.get(ref));
}
}
#Override
public void endElement(String uri, String localName,String qName) throws SAXException {
if (qName.equalsIgnoreCase("way")) {
ways.add(nodeBuffer);
}
}
#Override
public void endDocument() throws SAXException {
roads = ways;
}
};
saxParser.parse("file://" + Environment.getExternalStorageDirectory() + "/roadmap.xml", handler);
return roads;
}
}
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().
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.