解析java中的xml字符串?

时间:2010-10-11 13:59:24

标签: java xml

如何解析存储在java字符串对象中的xml?

Java的XMLReader仅解析URI或输入流中的XML文档。是否无法从包含xml数据的String中解析?

现在我有以下内容:

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

提前致谢

4 个答案:

答案 0 :(得分:41)

SAXParser可以readInputSource

InputSource 可以在其constructor

中使用阅读器

因此,您可以通过StringReader

放置解析XML字符串
new InputSource(new StringReader("... your xml here....")));

答案 1 :(得分:3)

尝试jcabi-xml(请参阅此blog post)并使用一行代码

XML xml = new XMLDocument("<document>...</document>")

答案 2 :(得分: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 "?";
  }
}

答案 3 :(得分:1)

您的XML可能很简单,可以使用DOM或SAX API手动解析,但我仍然建议使用XML序列化API,例如JAXBXStreamSimple相反,因为编写自己的XML序列化/反序列化代码是一种拖累。

请注意,XStream FAQ错误地声称您必须将生成的类与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