Best practices and design guidelines for writing XML in Java?

Several times I have encountered a task that requires the production of XML (smaller) Every time I wander:

What are the best practices for dynamically creating XML documents about easy coding, readable and maintainable code, performance and good design practices?

For example:

Is the connection string better? Or create a DOM tree and fill it? > ("programmatically") are there better ways to roll up the line of building XML, or are there many ways to deal with parts of its document? > It's best to use tools (which?) Or a backbone that generates XML from scratch every time?

I will appreciate it. If you can share some references, is there a well-known topic on this issue?

Solution

XML is more tricky than it looks Do not build it from a connection string Stax javax should be used when running the document xml. stream. XMLStreamWriter. In terms of memory usage, even large documents are very reasonable

For smaller documents, it's possible to create a DOM tree, but you actually prefer xmlstreamwriter

For smaller documents, you can also use an XML binding framework, such as JAXB, which is effectively the same as building a DOM tree, but allows you to write code according to the business domain rather than XML As a reward, you can use the same JAXB annotations as Jersey to generate JSON output and XML

This is the context, and your goal should be to maximize the readability of the source code In XML structure, repeated parts often get their own methods Long, flat parts of XML tend to use long Java programs

Some unusual indents may make the code easier to read:

private void write(XMLStreamWriter w) {
    //...
    w.writeStartElement("parentTag");
        w.writeStartElement("nestedTag"); 
        w.writeCharacters("body 1");
        w.writeEndElement(); 
    w.writeEndElement();
}

... but this is really close to the point where you should extract a help method

Using the xmlstreamwriter method or binding frameworks such as JAXB, I don't see the need to use a template system or something like that These frameworks are fully capable of writing preface.

If you have to inject a small portion of the generated XML into a larger static template, you may use a pre generated structure I think it's a marginal case, or I've never seen it before

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>