xmlhandler
xmlhandler

Reputation: 21

Modify existing XML stylesheet processing instruction in Java

I'm reading an existing XML file and outputting it (using DOM).

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="test"?>
<Books>
    <Book name="MyBook" />
</Books>

But how do I modify the XML stylesheet? -> href here set "test".

Upvotes: 2

Views: 1700

Answers (2)

Mads Hansen
Mads Hansen

Reputation: 66723

Something like this should work (untested)

Element root = doc.getDocumentElement();
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/processing-instruction('xml-stylesheet')";
ProcessingInstruction pi;
pi = (ProcessingInstruction)xpath.evaluate(expression, doc, XPathConstants.NODE);
pi.setData("type='text/xsl' href='foo.xsl'");

Upvotes: 4

Theresa Forster
Theresa Forster

Reputation: 1932

Thats a bit tricky, but why not read the file first into a String and do a replace before sending it via a stream into the dom parser.

Upvotes: 0

Related Questions