質問

Suppose I have a very simple input exmaple XML file as follows

<?xml version="1.0"?>
<content>
    <some />
</content>

I would like to modify the xml structure by inserting additional elements anywhere in the original structure, or replace an element with other content.

Can I somehow achieve that using EclipseLink MOXy? E.g. I want to to replace "some" by "someReplacement" and add "whatever".

<?xml version="1.0"?>
<content>
    <someReplacement>
        <more>information</more>
    </someRepaclement>
    <whatever />
</content>

The actual XML I want to process is more complex, however I only actually deal with a small subset of its content, so I would prefer not to unmarshall the complete file into a complex bean structure, make changes to a small set of elements, and marshall the whole structure back into a file. At least I don't want to know about the complexity.

This is because the input XML schema can vary greatly, but the specific elements I care about exist in each of these schema. So I would ideally want to find a solution to e.g. adapt XPaths in something like a bindings file to point to the elements I want to replace/insert.

I would prefer not to use JDOM, because the elements I produce for insertion/replacement are complex and I don't want to create them 'by hand' but instead have some bean structure be mapped.

Can I do this with MOXy? Any other JAXB provider? Should I use JDOM, or is there anything else that could help?

役に立ちましたか?

他のヒント

You should use XSLT. The reason XSLT was invented, was to modify XML structures.

Below is the code of perform this task in vtd-xml. VTD-XML is the only xml processing framework supporting incremental update...

Here is an article explaining this feature...

http://www.devx.com/xml/Article/36379

import java.io.*;
import com.ximpleware.*;

public class simpleUpdate {
    public static void main(String[] args) throws VTDException, IOException{
        // TODO Auto-generated method stub
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false))
            return;
        VTDNav vn = vg.getNav();
        XMLModifier xm = new XMLModifier(vn);
        if (vn.toElement(VTDNav.FC)){
            xm.remove();
            xm.insertAfterElement(" <someReplacement>\n<more>information</more>\n</someRepaclement><whatever/>");
            xm.output("output.xml");
        }
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top