I am using Java and XSL style sheets to retrieve values from an XML file and outputting it to a text file.
Below is the program used:
TransformerFactory factory = TransformerFactory.newInstance();
Source xslt = new StreamSource(new File("transform.xsl"));
Transformer transformer = factory.newTransformer(xslt);
Source text = new StreamSource(new File("inputXML.txt"));
transformer.transform(text, new StreamResult(new File("output.txt"))) ;
But recently I found that the XML files I will be reading will have 2 root nodes and not one. So I am thinking of doing string manipulation to add a root node of my own programatically so that I can avoid the below error:
ERROR: 'The markup in the document following the root element must be well-formed.' ERROR: 'com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: The markup in the document following the root element must be well-formed.'
But I am unable to do any String manipulation's on javax.xml.transform.Source (Casting is not working). I do not want to use intermediate files to add my root node as I fear it will prove costly as i need to be processing close to 50k XML records.
The StreamSource has several constructors
Path inputPath = Paths.get("inputXML.txt");
String input = new String(Files.readAllBytes(inputPath,
StandardCharsets.UTF_8));
input = input.replaceFirst("<quasiroot", "<root>$0")
+ "</root>";
Source text = new StreamSource(new StringReader(input));
Files#readString
(since Java 11):String input = Files.readAllString(inputPath);