7

I want to convert a String to org.jdom.Element

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

How can I do it?

Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
pseudo2188
  • 93
  • 1
  • 2
  • 6

3 Answers3

5

There is more than one way to parse XML from string:

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:

Using a SAXParser which can read an inputsource:

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

See: SAXParser, InputSource

Community
  • 1
  • 1
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
0
  1. Create a Document from your string. Look at JDOM FAQ: How do I construct a Document from a String?
  2. Use method Document.getRootElement() to access the root element.

(You mentioned package org.jdom so I assume you work with JDOM 1.1.)

vanje
  • 10,180
  • 2
  • 31
  • 47
  • I usually do this, but for my exemple it not necessary, cause, I have to declare namespaces that I used, and construct a valid XML – pseudo2188 Apr 11 '13 at 15:20
-1

I recommend you use the Simple XML Framework from http://simple.sourceforge.net/.With this framework you can serialize and deserialize your objects easily. I hope this information can be important for you.

mandisk
  • 24
  • 1
  • 3