在java中解析一个xml字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3906892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:38:56  来源:igfitidea点击:

parse an xml string in java?

javaxml

提问by Jonathan

how do you parse xml stored in a java string object?

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

Java's XMLReader only parses XML documents from a URI or inputstream. is it not possible to parse from a String containing an xml data?

Java 的 XMLReader 仅解析来自 URI 或输入流的 XML 文档。是否无法从包含 xml 数据的字符串中进行解析?

Right now I have the following:

现在我有以下几点:

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

And on my handler i have this:

在我的处理程序上,我有这个:

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

Thanks in advance

提前致谢

采纳答案by Pierre

The SAXParsercan readan InputSource.

SAXParser的可以读取的InputSource

An InputSourcecan take a Readerin its constructor

一个InputSource的可以采取读者在其构造

So, you can put parse XML string via a StringReader

因此,您可以通过StringReader放置解析 XML 字符串

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

回答by Júlio Santos

Take a look at this: http://www.rgagnon.com/javadetails/java-0573.html

看看这个: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 "?";
  }
}

回答by rob

Your XML might be simple enough to parse manually using the DOM or SAX API, but I'd still suggest using an XML serialization API such as JAXB, XStream, or Simpleinstead because writing your own XML serialization/deserialization code is a drag.

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

Note that the XStream FAQ erroneously claims that you must use generated classes with JAXB:

请注意,XStream FAQ 错误地声称您必须将生成的类与 JAXB 一起使用:

How does XStream compare to JAXB (Java API for XML Binding)?

JAXB is a Java binding tool. It generates Java code from a schema and you are able to transform from those classes into XML matching the processed schema and back. Note, that you cannot use your own objects, you have to use what is generated.

XStream 与 JAXB(用于 XML 绑定的 Java API)相比如何?

JAXB 是一个 Java 绑定工具。它从模式生成 Java 代码,您可以将这些类转换为与处理后的模式匹配的 XML 并返回。请注意,您不能使用自己的对象,您必须使用生成的对象。

It seems this was true was true at one time, but JAXB 2.0 no longer requires you to use Java classes generated from a schema.

似乎这曾经是真的,但 JAXB 2.0 不再要求您使用从模式生成的 Java 类。

If you go this route, be sure to check out the side-by-side comparisons of the serialization/marshalling APIs I've mentioned:

如果你走这条路,一定要查看我提到的序列化/编组 API 的并排比较:

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

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

回答by yegor256

Try jcabi-xml(see this blog post) with a one-liner:

使用单行尝试jcabi-xml(请参阅此博客文章):

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