Java 中的 XML 模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1680175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:35:00  来源:igfitidea点击:

XML template in Java

javaxmltemplates

提问by RJ.

I need to generate XMLand they differ only in the values, that the tags contain.

我需要生成XML,它们仅在标签包含的值上有所不同。

Is it possible to create a template XMLand then write only the values each time? (I do not want to go the JAXBway as these are small XMLs and are not worth creating objects for them).

是否可以创建一个模板XML,然后每次只写入值?(我不想走这JAXB条路,因为它们很小XML,不值得为它们创建对象)。

Is this a good approach?

这是一个好方法吗?

Any thoughts?

有什么想法吗?

回答by Carl Smotricz

As long as the XML file to be produced is small, simple and mostly consistent in format, I tend to buck the trend: I simply create and write a text string.

只要要生成的 XML 文件小、简单且格式基本一致,我就倾向于逆势而上:我只是创建并编写一个文本字符串。

writer.out.format("<?xml version='1.0'><root><tag1>%s</tag1></root>", value1)

kinda thing.

有点东西。

回答by fijiaaron

You can use freemarkeror velocityfor templating in java -- or even just add PHP tags to a sample XML to generate from a template.

您可以在 Java 中使用freemarkerVelocity进行模板化——或者甚至只是将 PHP 标签添加到示例 XML 以从模板生成。

I think as a general rule, though, once you start conditionally adding elements or attributes, or looping to generate multiples, you're better of generating your XML -- though I agree sometimes getting it into a format you want (not what the generator wants) is sometimes a pain.

不过,我认为作为一般规则,一旦您开始有条件地添加元素或属性,或循环以生成倍数,您最好生成 XML——尽管我同意有时将其转换为您想要的格式(而不是生成器的格式)想要)有时是一种痛苦。

回答by Yaneeve

Despite the fact that you are against jaxb (which I have yet to use), I wish to recommend a comparable way to do this with Apache's XMLBeans.

尽管您反对 jaxb(我还没有使用过),但我还是希望推荐一种类似的方法来使用Apache 的 XMLBeans来做到这一点。

This requires you to use an xml schema - but from my experience it worth it...

这需要您使用 xml 模式 - 但根据我的经验,这是值得的......