Класс описывающий произвольный елемент с хмл:
| Код | import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set;
public class Element { private String name = null; private HashMap<String,String> attributes = null; private List<Element> subElements = null; private String content = ""; private final int nesting;
public Element(String name,int nesting) { this.name = name; this.nesting = nesting; } public void setContent(String content){ if (content==null || getTextFromString(content).length()==0) return; this.content = getTextFromString(content); } public void addContent(String content){ if (content==null || getTextFromString(content).length()==0) return; if (this.content==null || this.content.equals("")) this.content = getTextFromString(content); else this.content = this.content + getTextFromString(content); } public HashMap<String,String> getAttributes(){ if (attributes == null){ attributes = new HashMap<String, String>(); } return attributes; } public List<Element> getElements(){ if (subElements == null){ subElements = new ArrayList<Element>(); } return subElements; } public void addElement(Element element){ getElements().add(element); } public void addElements(List<Element> elements){ getElements().addAll(elements); } public void addAttribute(String atName,String atValue){ getAttributes().put(atName, atValue); } public void addAttributes(HashMap<String,String> attributes){ getAttributes().putAll(attributes); } public String getName(){ return name; } public String getContent(){ return content; } public String toString(){ return tabs()+"<"+getName()+" "+getAttributeList()+">"+ (getContent().length()>0 ? "\n\t"+tabs()+getContent():"")+ getElementsList()+ "\n"+tabs()+"</"+getName()+">"; } private String getElementsList(){ StringBuilder sb = new StringBuilder(); for (Element elem: getElements()){ sb.append("\n"+elem); } return sb.toString(); } private String getAttributeList(){ StringBuilder sb = new StringBuilder(); try{ Set<String> set = getAttributes().keySet(); Iterator<String> iter = set.iterator(); while (iter.hasNext()){ String tKey = iter.next(); if (sb.length()==0) sb.append(tKey+"=\""+getAttributes().get(tKey)+"\""); else sb.append(" "+tKey+"=\""+getAttributes().get(tKey)+"\""); } } catch(Exception e){ e.printStackTrace(); } return sb.toString(); } private String tabs(){ StringBuilder sb = new StringBuilder(); for (int i =0;i<nesting;i++){ sb.append("\t"); } return sb.toString(); } private String getTextFromString(String text){ StringBuilder sb = new StringBuilder(text); if (sb.length()>0){ while (sb.length()>0 && (sb.charAt(0)=='\n' || sb.charAt(0)=='\r' || sb.charAt(0)=='\t')){ sb.deleteCharAt(0); } while (sb.length()>0 && (sb.charAt(sb.length()-1)=='\n' || sb.charAt(sb.length()-1)=='\r' || sb.charAt(sb.length()-1)=='\t')){ sb.deleteCharAt(sb.length()-1); } } return sb.toString(); } public List<Element> getElements(String name){ return getElements(name,0); } public List<Element> getElements(String name,int afterInd){ List<Element> list =getElements(); List<Element> newList =new ArrayList<Element>(); if (list.size()==0) return null; if (afterInd<0 || afterInd>=list.size()) throw new IndexOutOfBoundsException("Index "+afterInd+" is out of bound("+(list.size()-1)+")"); for (int i = afterInd; i<list.size();i++){ if (list.get(i).getName().equals(name)) newList.add(list.get(i)); } return newList; } public Element getElement(String name){ return getElement(name,0); } public Element getElement(String name,int afterInd){ List<Element> list = getElements(); if (list.size()==0) return null; if (afterInd<0 || afterInd>=list.size()) throw new IndexOutOfBoundsException("Index "+afterInd+" is out of bound("+(list.size()-1)+")"); for (int i = afterInd; i<list.size();i++){ if (list.get(i).getName().equals(name)) return list.get(i); } return null; } }
|
Парсер:
| Код | import java.util.ArrayList; import java.util.List;
import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler;
public class SAXHandler extends DefaultHandler { private List<Element> elements=null; private int nesting; private String elementName = null; public SAXHandler(String elementName) throws Exception { if (elementName==null || elementName.length()<1) throw new Exception("Element name not specified!"); this.elementName = elementName; nesting = -1; } public List<Element> getElements(){ if (elements==null){ elements = new ArrayList<Element>(); } return elements; } @Override public void startDocument() throws SAXException { elements = new ArrayList<Element>(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (nesting == -1){ if (elementName.equals(qName)){ Element tElem = new Element(qName,nesting+1); addAttributesToElement(tElem, attributes); getElements().add(tElem); nesting++; } } else { try { Element tElem = new Element(qName,nesting+1); addAttributesToElement(tElem, attributes); getElementFor(nesting).addElement(tElem); nesting++; } catch (Exception e) { } } } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (nesting==-1) return; Element curr = null; try { curr = getElementFor(nesting); } catch (Exception e) { e.printStackTrace(); } if(curr!=null){ curr.addContent(new String(ch, start, length)); } }
@Override public void endElement(String uri, String localName, String qName) throws SAXException { if (nesting!=-1) --nesting; } private Element getLast(){ List<Element> list = getElements(); if (list.size()>0){ return list.get(list.size()-1); } return null; } private Element getElementFor(int nestingLevel) throws Exception{ if (nestingLevel<0 && nestingLevel>this.nesting) throw new Exception("Incorect nesting level "+nestingLevel+" of "+this.nesting); Element curr = getLast(); while (nestingLevel>0){ curr = getLastSubElement(curr); nestingLevel--; } return curr; } private Element getLastSubElement(Element parent){ if (parent!=null) { List<Element> subElements = parent.getElements(); if (subElements.size()>0) return subElements.get(subElements.size()-1); } return null; } private void addAttributesToElement(Element elem, Attributes attributes){ int count = attributes.getLength(); for (int i=0;i<count;i++){ elem.addAttribute(attributes.getQName(i), attributes.getValue(i)); } } }
|
Пример парсинга:
| Код | String s = <твой хмл> InputStream in = new ByteArrayInputStream(s.getBytes("UTF-8")); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser=null; try { parser = factory.newSAXParser(); } catch (Exception e) { throw e; } SAXHandler handler; try { handler = new SAXHandler("FORECAST"); parser.parse(in, handler); List<Element> agr = handler.getElements()) } catch (Exception e){}
|
| Цитата | Я сделал класс FORECAST с полями типа String(куда хочу записать атрибуты) day,month,year,hour,tod, predict,weekday и поля пользовательских типов PHENOMENA, PRESSURE, TEMPERATURE, WIND,RELWET,HEAT( которые в свою очередь содержат в полях типа String атрибуты соответствующих тэгов из xml).
|
Можешь реализовать свои классы описывающие елементы таким образом, чтоб в конструктор передавалась ссылка на Element, и в конструкторе инициализировать необходимые поля.
Например:
| Код | public class Forecast{ private String day; private String month; private String year; ................................... private Phenomena phenomena = null; public Forecast(Element element) throws Exception{ day=element.getAttributes().get("day"); if (day== null) throw new Exception("can't parse day");
month=element.getAttributes().get("month"); if (month == null) throw new Exception("can't parse month");
.................................... phenomena = new Phenomena (element.getElement("PHENOMENA")); ...................................
}
public String getDay() { return day; }
public String getMonth() { return month; } ........................ public Phenomena getPhenomena(){ return phenomena; } }
|
|