Jean-Charles DUFOUR wrote:
> I'm also very interesting about "how to parse a xml string", but I'm a
> newbie both with java and xerces (what a challenge!!!)
> May you please write the code sample to change the initial code produce by
> Gude Reshma  and then show me how to < use the "getBytes(String)" > or <use
> a StringReader instead>

Sorry, I should have done this to begin with.

  String XML_STRING = "<root/>";

InputStream method:

  byte[] bytes = XML_STRING.getBytes("UTF8");
  InputStream stream = new ByteArrayInputStream(bytes);
  InputSource source = new InputSource(stream);
  // parse document with input source

Reader method:

  Reader reader = new StringReader(XML_STRING);
  InputSource source = new InputSource(reader);
  // parse document with input source

NOTE: You should always set the systemId of the input source
before parsing so that the parser is able to find resources
(like the DTD) that are relative to the input document. This
approach can be combined with a custom entity resolver to
parse the DTD from a String as well.

For example, first a custom entity resolver:

  public class MyEntityResolver implements Entity Resolver {
    public InputSource resolveEntity(String pubid, String sysid)
      throws SAXException, IOException {
      if (sysid.equals("http://example.com/xml/grammar.dtd";)) {
        String DTD_STRING = "<!ENTITY root EMPTY>";
        StringReader reader = new StringReader(DTD_STRING);
        InputSource source = new InputSource(reader);
        source.setSystemId("http://example.com/xml/grammar.dtd";);
        return source;
      }
      return null;
    }
  }

Next, the parser that uses it:

  String XML_STRING = "<!DOCTYPE root SYSTEM
'http://example.com/xml/grammar.dtd'>\n<root/>";

  DOMParser parser = new DOMParser();
  parser.setEntityResolver(new MyEntityResolver());

I'm instantiating an example parser directly but you can set
an entity resolver on the parsers returned by JAXP as well.

Hope this helps!

-- 
Andy Clark * [EMAIL PROTECTED]

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to