Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String to a xml Element java

Tags:

java

xml

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?

like image 790
pseudo2188 Avatar asked Apr 11 '13 11:04

pseudo2188


People also ask

Can we convert string to XML in Java?

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.


1 Answers

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

like image 150
CloudyMarble Avatar answered Sep 28 '22 21:09

CloudyMarble