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>";
1
  • 1
    What you are trying to do is very unclear. If you already have a string - why would you even need a XML parser? Commented Dec 14, 2010 at 7:48

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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
3

You can use StringReader :

StringReader sr = new StringReader(xml);
InputSource is = new InputSource(sr);
Document d = builder.parse(is);

2 Comments

Should the second line be InputSource is = new InputSource(sr); instead?
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.