diff --git a/jOOQ/src/main/java/org/jooq/DSLContext.java b/jOOQ/src/main/java/org/jooq/DSLContext.java index adc53d117a..6a271b8361 100644 --- a/jOOQ/src/main/java/org/jooq/DSLContext.java +++ b/jOOQ/src/main/java/org/jooq/DSLContext.java @@ -3726,6 +3726,31 @@ public interface DSLContext extends Scope , AutoCloseable { @Support Result fetchFromJSON(String string); + /** + * Fetch all data from an XML string. + *

+ * This is the inverse of calling {@link Result#formatXML()}. Use the + * various conversion methods to retrieve other data types from the + * Result: + *

+ *

+ * Missing values result in null. Empty values result in empty + * Strings + * + * @param string The XML string + * @return The transformed result. This will never be null. + * @throws DataAccessException If anything went wrong parsing the XML file + */ + @Support + Result fetchFromXML(String string); + /** * Fetch all data from a list of strings. *

diff --git a/jOOQ/src/main/java/org/jooq/impl/DefaultDSLContext.java b/jOOQ/src/main/java/org/jooq/impl/DefaultDSLContext.java index f313b62e8c..5dd34b760c 100644 --- a/jOOQ/src/main/java/org/jooq/impl/DefaultDSLContext.java +++ b/jOOQ/src/main/java/org/jooq/impl/DefaultDSLContext.java @@ -61,6 +61,7 @@ import static org.jooq.impl.Tools.blocking; import static org.jooq.impl.Tools.list; import static org.jooq.tools.Convert.convert; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.Serializable; import java.io.StringReader; @@ -88,6 +89,8 @@ import java.util.function.Function; import java.util.stream.Stream; import javax.sql.DataSource; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; import org.jooq.AlterIndexOnStep; import org.jooq.AlterIndexStep; @@ -1451,9 +1454,8 @@ public class DefaultDSLContext extends AbstractScope implements DSLContext, Seri } finally { try { - if (reader != null) { + if (reader != null) reader.close(); - } } catch (IOException ignore) {} } @@ -1461,6 +1463,22 @@ public class DefaultDSLContext extends AbstractScope implements DSLContext, Seri return fetchFromStringData(list); } + @Override + public Result fetchFromXML(String string) { + try { + SAXParserFactory factory = SAXParserFactory.newInstance(); + SAXParser saxParser = factory.newSAXParser(); + // TODO: Why does the SAXParser replace \r by \n? + + XMLHandler handler = new XMLHandler(this); + saxParser.parse(new ByteArrayInputStream(string.getBytes()), handler); + return handler.result; + } + catch (Exception e) { + throw new DataAccessException("Could not read the XML string", e); + } + } + @Override public Result fetchFromStringData(String[]... strings) { return fetchFromStringData(list(strings), true);