将String转换为xml元素java

时间:2013-04-11 11:01:01

标签: java xml

我想将字符串转换为org.jdom.Element

String s = "<rdf:Description rdf:about=\"http://dbpedia.org/resource/Barack_Obama\">";

我该怎么做?

3 个答案:

答案 0 :(得分:4)

从字符串中解析XML的方法不止一种:

Example 1

  String xml = "Your XML";
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));     

Example 2

使用可以读取输入源的SAXParser:

 SAXParserFactory factory = SAXParserFactory.newInstance();
 SAXParser saxParser = factory.newSAXParser();
 DefaultHandler handler = new DefaultHandler() {
 saxParser.parse(new InputSource(new StringReader("Your XML")), handler);    

请参阅:SAXParserInputSource

答案 1 :(得分:0)

  1. 从字符串中创建Document。查看JDOM FAQ:How do I construct a Document from a String?
  2. 使用方法Document.getRootElement()访问根元素。
  3. (你提到了包org.jdom所以我假设你使用JDOM 1.1。)

答案 2 :(得分:-1)

我建议你使用http://simple.sourceforge.net/.With这个框架中的Simple XML Framework,你可以轻松地序列化和反序列化你的对象。我希望这些信息对您来说很重要。