1

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.

DS.
  • 604
  • 2
  • 6
  • 24

1 Answers1

1

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:

        StringBuilder sb = new StringBuilder();
        sb.append("<tag xmlns:tsip=\"http://schemas.thomson.com/ts/20041221/tsip\">");
        String xmlFrag = new String(Files.readAllBytes(Paths.get("C:/myFileName")));
        sb.append(xmlFrag);
        sb.append("</tag>");
        Builder parser = new Builder();
        Document doc = parser.build(sb.toString(), null);

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.

        Element wrapperRoot = doc.getRootElement();
        Element realRoot = root.getFirstChildElement("publications");

Then use XOM as normal to write out he revised fragment.

Wee Shetland
  • 955
  • 8
  • 18
  • Thanks Tony. I did think of that solution but it seemed a bit convoluted and possibly a bit slow. Anyway, since the xml fragment is quite basic in the end I just used simple String manipulation (no xom) – DS. Aug 11 '15 at 09:38