Search code examples
javaxmljoox

Parse Xml String with Joox


How do I parse a Xml String with jOOx? The parse method accepts String uri, but not Xml String.


Solution

  • Looks like you can do it using the JOOX class and a StringReader. For example:

    String xml = "<?xml version='1.0'?><root><child attr='attr' /></root>";
    StringReader sr = new StringReader( xml );
    Match m = JOOX.builder().parse( sr );
    

    See the DocumentBuilder API, which JOOX uses.

    You might have to convert the StringReader to an InputSource or equivalent, but that's a relatively trivial conversion. From the test case:

        xmlExampleString = IOUtil.toString(JOOXTest.class.getResourceAsStream("/example.xml"));
        xmlExampleDocument = builder.parse(new ByteArrayInputStream(xmlExampleString.getBytes()));
    

    In this case, you could write:

    String xml = "<?xml version='1.0'?><root><child attr='attr' /></root>";
    StringReader sr = new StringReader( xml );
    ByteArrayInputStream bais = new ByteArrayInputStream( new InputStreamReader( sr ) );
    document = builder.parse( bais );
    

    That should get you started. Note that there are probably simpler ways to convert a String to an input stream.