简体   繁体   中英

comparing two xml files for specific elements — in java

I've tried avoiding asking this question for as long as possible... but I haven't found anything that will fit my needs perfectly, and it's about time I get this project done.

So here's what I need:

I'm making an app that will basically diff two xml documents, and then make minor changes to one of them. I have a template xml, and then the other xml file will change each time. I only have to determine whether or not the key elements from the template are in the other file. Any extra stuff can be ignored, but missing key elements should be added.

Visual representation:

template

<root attribute="asd">
    <a />
    <b>
        <c asdf="fdsa" />
    </b>
</root>

other xml

<root>
    <a d="wer" />
    <b>
        <c />
    <b>
    <d />
</root>

final result:

<root attribute="asd">
    <a d="wer" />
    <b>
        <c asdf="fdsa" />
    </b>
    <d />
</root>

My question:

Is there any way to accomplish this final result without painstakingly going through every key element and making sure they exist? I've looked into XPath, and this seems like my best solution so far, simply checking to see if necessary parts are present, and then adding them if they aren't (I'd be making a new file, so writing in new elements isn't terribly troublesome). However, since there are a LOT of things I'd have to check for, I'd rather not do this. I also looked at XMLUnit and XOM, but those seem better suited to comparing and telling me the differences (including where extra lines have been added, which I'm not interested in).

So, any great idea to implement two lines of code and have this just magically accomplish itself? Cuz that would be great :)

You should be able to do this using XSLT, I would have thought. Not two lines of code - no code at all, just a suitable definition of the merge heuristics in your XSLT file.

See similar issue discussed and solved here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM