Parse Xml String with Joox

2.3k Views Asked by At

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

2

There are 2 best solutions below

0
Dave Jarvis On BEST ANSWER

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.

0
kakoni On

In the simplest form it looks like this

// Parse the document from string
Document document = $(new StringReader("<?xml version='1.0'?><root><child attr='attr' /></root>")).document();

And then do your matching with

// Wrap the document with the jOOX API and find root element
Match m = $(document).find("root");