2010-10-11 157 views
19

你如何解析存儲在java字符串對象中的xml?解析java中的xml字符串?

Java的XMLReader僅解析來自URI或輸入流的XML文檔。是不是可以從包含xml數據的字符串解析?

現在,我有以下幾點:

try { 
    SAXParserFactory factory = SAXParserFactory.newInstance(); 
    SAXParser sp = factory.newSAXParser(); 
    XMLReader xr = sp.getXMLReader(); 

    ContactListXmlHandler handler = new ContactListXmlHandler(); 
    xr.setContentHandler(handler); 
    xr.p 
} catch (ParserConfigurationException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (SAXException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

而且對我的處理程序,我有這樣的:提前

public class ContactListXmlHandler extends DefaultHandler implements Resources { 

    private List<ContactName> contactNameList = new ArrayList<ContactName>(); 

    private ContactName contactItem; 

    private StringBuffer sb; 

    public List<ContactName> getContactNameList() { 
     return contactNameList; 
    } 

    @Override 
    public void startDocument() throws SAXException { 
     // TODO Auto-generated method stub 
     super.startDocument(); 

     sb = new StringBuffer(); 
    } 

    @Override 
    public void startElement(String uri, String localName, String qName, 
      Attributes attributes) throws SAXException { 
     // TODO Auto-generated method stub 
     super.startElement(uri, localName, qName, attributes); 
     if(localName.equals(XML_CONTACT_NAME)){ 
      contactItem = new ContactName(); 
     } 

     sb.setLength(0); 

    } 

    @Override 
    public void characters(char[] ch, int start, int length){ 
     // TODO Auto-generated method stub 
     try { 
      super.characters(ch, start, length); 
     } catch (SAXException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     sb.append(ch, start, length); 
    } 

    @Override 
    public void endDocument() throws SAXException { 
     // TODO Auto-generated method stub 
     super.endDocument(); 
    } 

    /** 
    * where the real stuff happens 
    */ 
    @Override 
    public void endElement(String uri, String localName, String qName) 
      throws SAXException { 
     // TODO Auto-generated method stub 
     //super.endElement(arg0, arg1, arg2); 

     if(contactItem != null){ 
      if (localName.equalsIgnoreCase("title")) { 
       contactItem.setUid(sb.toString()); 
       Log.d("handler", "setTitle = " + sb.toString()); 

      } else if (localName.equalsIgnoreCase("link")) { 
       contactItem.setFullName(sb.toString()); 

      } else if (localName.equalsIgnoreCase("item")){ 
       Log.d("handler", "adding rss item"); 
       contactNameList.add(contactItem); 
      } 

      sb.setLength(0); 
     } 
} 

感謝

+1

你可以看看這個:http://stackoverflow.com/questions/247161/how-do-i-turn-a-string-into-a-stream-in -java – foret 2010-10-11 14:00:58

回答

1

看看這個:http://www.rgagnon.com/javadetails/java-0573.html

import javax.xml.parsers.*; 
import org.xml.sax.InputSource; 
import org.w3c.dom.*; 
import java.io.*; 

public class ParseXMLString { 

    public static void main(String arg[]) { 
    String xmlRecords = 
     "<data>" + 
     " <employee>" + 
     " <name>John</name>" + 
     " <title>Manager</title>" + 
     " </employee>" + 
     " <employee>" + 
     " <name>Sara</name>" + 
     " <title>Clerk</title>" + 
     " </employee>" + 
     "</data>"; 

    try { 
     DocumentBuilderFactory dbf = 
      DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db = dbf.newDocumentBuilder(); 
     InputSource is = new InputSource(); 
     is.setCharacterStream(new StringReader(xmlRecords)); 

     Document doc = db.parse(is); 
     NodeList nodes = doc.getElementsByTagName("employee"); 

     // iterate the employees 
     for (int i = 0; i < nodes.getLength(); i++) { 
      Element element = (Element) nodes.item(i); 

      NodeList name = element.getElementsByTagName("name"); 
      Element line = (Element) name.item(0); 
      System.out.println("Name: " + getCharacterDataFromElement(line)); 

      NodeList title = element.getElementsByTagName("title"); 
      line = (Element) title.item(0); 
      System.out.println("Title: " + getCharacterDataFromElement(line)); 
     } 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
    /* 
    output : 
     Name: John 
     Title: Manager 
     Name: Sara 
     Title: Clerk 
    */  

    } 

    public static String getCharacterDataFromElement(Element e) { 
    Node child = e.getFirstChild(); 
    if (child instanceof CharacterData) { 
     CharacterData cd = (CharacterData) child; 
     return cd.getData(); 
    } 
    return "?"; 
    } 
} 
1

你的XML可能是很簡單的手工解析使用把解析XML字符串DOM或SAX API,但我仍然建議使用XML序列化API,例如JAXB,XStreamSimple,而不是因爲編寫自己的XML序列化/請求者ialization代碼是一個拖動。

注意,XStream的常見問題錯誤地聲稱,您必須使用生成的類與JAXB:

如何XStream的比較JAXB(用於XML綁定的Java API)?

JAXB是一個Java綁定工具。它從一個模式生成Java代碼,您可以將這些類轉換爲匹配處理後的模式的XML並返回。請注意,你不能使用自己的對象,你必須使用生成的東西。

似乎這是事實,但JAXB 2.0不再要求您使用從模式生成的Java類。

如果你走這條路,一定要檢查出系列化的並排側比較/編組我所提到的API:

http://blog.bdoughan.com/2010/10/how-does-jaxb-compare-to-xstream.html http://blog.bdoughan.com/2010/10/how-does-jaxb-compare-to-simple.html