2010-10-11 33 views
19

làm cách nào để phân tích cú pháp xml được lưu trữ trong đối tượng chuỗi java?phân tích chuỗi xml trong java?

XMLReader của Java chỉ phân tích cú pháp tài liệu XML từ URI hoặc luồng nhập. sao không thể phân tích cú pháp từ một Chuỗi chứa dữ liệu xml?

Ngay bây giờ tôi có như sau:

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(); 
} 

Và trên xử lý của tôi có điều này:

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); 
     } 
} 

Cảm ơn trước

+1

Bạn có thể xem xét điều này: http://stackoverflow.com/questions/247161/how-do-i-turn-a-string-into-a-stream-in -java – foret

Trả lời

41

SAXParser có thể read an InputSource.

Một InputSource có thể mất một đọc trong constructor

của nó Vì vậy, bạn có thể đặt chuỗi XML phân tích cú pháp thông qua một StringReader

new InputSource(new StringReader("... your xml here...."))); 
+1

ch eers mate. dường như đã làm việc. – jonney

1

Hãy xem này: 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 của bạn có thể đủ đơn giản để phân tích cú pháp bằng tay bằng cách sử dụng API DOM hoặc SAX, nhưng tôi vẫn khuyên bạn nên sử dụng API tuần tự hóa XML như JAXB, XStream hoặc Simple thay vì viết XML serialization/deser của riêng bạn mã ialization là một kéo.

Lưu ý rằng xStream FAQ sai lầm cho rằng bạn phải sử dụng các lớp học được tạo ra với JAXB:

Làm thế nào để so sánh với XStream JAXB (Java API cho XML Binding)?

JAXB là công cụ liên kết Java. Nó tạo ra mã Java từ một lược đồ và bạn có thể chuyển đổi từ các lớp đó thành XML khớp với lược đồ đã xử lý và ngược lại. Lưu ý rằng bạn không thể sử dụng các đối tượng của riêng mình, bạn phải sử dụng những gì được tạo.

Dường như điều này đúng là đúng một lúc, nhưng JAXB 2.0 không còn yêu cầu bạn sử dụng các lớp Java được tạo từ một lược đồ nữa.

Nếu bạn đi tuyến đường này, hãy chắc chắn kiểm tra side-by-side so sánh của serialization/marshalling API tôi đã đề cập:

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

Các vấn đề liên quan