17

I use the following code to parse the XML file.

DocumentBuilderFactory factory;
DocumentBuilder builder;
InputStream is;
Document dom;
try {
    factory = DocumentBuilderFactory.newInstance();
    is = new FileInputStream(strFileName);
    builder = factory.newDocumentBuilder();

    dom = builder.parse(is);
}
catch(Exception e){}

Instead of XML file is there any way to parse the String.

String xml="<?xml version="1.0"?> <name> Application</name> <demo> Demo </demo> </xml>";
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
RMK
  • 247
  • 1
  • 5
  • 10
  • 1
    What you are trying to do is very unclear. If you already have a string - why would you even need a XML parser? – Ofir Dec 14 '10 at 07:48

2 Answers2

30

You can convert your string to an InputStream using ByteArrayInputStream:

String xml ="valid xml here";
InputStream is = new ByteArrayInputStream(xml.getBytes("UTF-8"));

dom = builder.parse(is);
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
  • i get this problem while using your code java.lang.NullPointerException: Attempt to invoke virtual method 'org.w3c.dom.Document javax.xml.parsers.DocumentBuilder.parse(org.xml.sax.InputSource)' on a null object reference – phrogg Mar 26 '18 at 08:57
3

You can use StringReader :

StringReader sr = new StringReader(xml);
InputSource is = new InputSource(sr);
Document d = builder.parse(is);
Valentin Rocher
  • 11,667
  • 45
  • 59
  • Should the second line be `InputSource is = new InputSource(sr);` instead? – Bill Carey Feb 16 '11 at 21:48
  • i get this problem while using your code java.lang.NullPointerException: Attempt to invoke virtual method 'org.w3c.dom.Document javax.xml.parsers.DocumentBuilder.parse(org.xml.sax.InputSource)' on a null object reference – phrogg Mar 26 '18 at 08:56