开发者

Easiest parser in Java for xml to generate code for newcomer in xml

Guys I'm new to xml in Java.

I have the following task. I need to parse some xml files (specificallyh xcb-proto [X11]) to generate the equivalent request protocol in java. There is already a well defined xsd and the respective xml for the protocol. What is the best and easiest approach/parser to solve this?

Example of existant xml content:

  <request name="SetScreenSaver" opcode="107">
    <pad bytes="1" />
    <field type="INT16" name="timeout" />
    <field type="INT16" name="interval" />
    <field type="CARD8" name="prefer_blanking" enum="Blanking" />
    <field type="CARD8" name="allow_exposures" enum="Exposures" />
  </request>

This will generate a Java DOM (?) Object. And them with this I need to generate the given code in Java. For this case is:

Desired output:

public void setScreenSaver(int timeout, int interval, int preferBlanking, int allowExposures) {
    RequestOutputStream o = outputStream;
    synchronized (o) {
        o.beginRequest(107, 0, 1); // Major Opcode , Minor Opcode, ReqLength
        o.writeInt16(timeout);
        o.writeInt16(interval);
        o.writeInt8(preferBlanking);
        o.writeInt8(allowExposures);
        o.send();
    }
}

It seems that XSOM is the one that gives the easier approach...

PS: I have never manipulated xml files in J开发者_如何学Goava :3


You should look into JAXB. It comes with a utility that will generate all your Java code using the .XSD file to determine the structure.


Even with an XSD parser, this is never going to be an easy task, especially if the schema uses some of the more difficult aspects of the XSD language.

If this is a once-off task and the XSDs are not huge, then you are probably better of just writing the Java code by hand.

EDIT

I can think of one roundabout approach using Eclipse / EMF that might simplify things:

  1. Use the EMF tooling to create a EMF ECore model from the XSD. This gives you an in-memory "object model" analogous to simple UML.
  2. Using EMF infrastructure (e.g. JET), create a custom generator that traverses the ECore model and generates your target code.

The XSD to ECore also gives you (for free) generated classes for representing your XML in memory, editing it in a tree editor and reading/writing the XML. Associated technologies deal with persistence in a database, validation, model-to-model transformation, and other things.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜