I have a file containing an xml fragment. I need to add a child element into this file and resave it. I'm trying to use xom in Java (1.6). The problem is that the data in the file contains a namespace prefix so when I construct my Document object I get :
[Fatal Error] tsip:1:33: The prefix "tsip" for attribute "tsip:action" associated with an element type "publications" is not bound.
The file contains eg:
<publications tsip:action="replace">
<publication tsip:dw="000000" tsip:status="dwpi:equivalent" tsip:lang="ja" tsip:drawings="0">
<documentId>
<number tsip:form="dwpi">58071346</number>
<countryCode>JP</countryCode>
<kindCode>A</kindCode>
</documentId>
</publication>
</publications>
My Java code is :
FileInputStream fisTargetFile;
// Read file into a string
fisTargetFile = new FileInputStream(new File("C:\myFileName"));
pubLuStr = IOUtils.toString(fisTargetFile, "UTF-8");
Document doc = new Builder().build(pubLuStr, ""); // This fails
I suspect I need to make the code namespace aware ie add something like:
doc.getRootElement().addNamespaceDeclaration("tsip", "http://schemas.thomson.com/ts/20041221/tsip");
but I can't see how to do this BEFORE i create the Document doc. Any help , suggestions, appreciated.
One solution is to read the xml fragment into a string, and then wrap it in a dummy tag containing the namespace declaration. For example:
You can then happily parse the string into an XOM Document, and add the required changes before saving the revised fragment. To strip out the wrapper you can use XOM to pull out the fragment from the document by searching for the first real tag, e.g.
Then use XOM as normal to write out he revised fragment.