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?
Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With