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?

2
  • 1
    What did you try already? Commented Apr 11, 2013 at 11:03
  • Usually, I create a Document with root... Commented Apr 11, 2013 at 11:50

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

6 Comments

No, it doesn't work, cause this intruction only set the name of the element.
@Abu why should this be a comment?
@pseudo2188 it returns an org.jdom.Element from the string whats the output you expect?
I think, the OP wants to parse a whole XML document which is contained in the string.
Not the whole document, in my input, I have a String, but this String corresponds to an XML element, I have to compare it with other variables witch are really XML elements, so I have to convert the first one
|
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.)

1 Comment

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
-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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.