简体   繁体   English

读取和编辑xml文件的最有效方法

[英]Most efficient way to read and edit an xml file

I have an xml template file, some fields are blank and need to be filled by my application. 我有一个xml模板文件,某些字段为空白,需要由我的应用程序填充。 This has to result in an xml string representation of that file which will be given to another routine. 这必须导致该文件的xml字符串表示形式,并将其提供给另一个例程。

So, let's take this simple xml as example: 因此,让我们以这个简单的xml为例:

<root>
   <name anAttr=""></name>
   <age></age>
</root>

As you can see I'd have to read the xml and, in the parsing process, add some contents to it. 如您所见,我必须阅读xml,然后在解析过程中向其中添加一些内容。

I though about using a sax parser and in the handler I would do something like this: 我虽然要使用一个萨克斯解析器,但在处理程序中我会做这样的事情:

StringBuilder finalXml = new StringBuilder();

DefaultHandler handler = new DefaultHandler(){

        public void startElement(String uri, String localName,String qName, 
                Attributes attributes) throws SAXException {
                            finalXml.append("<"+qName+">");
                            if(qName.equals("name")){
                                finalXml.append("donald");
                             }

        }

would it be correct/efficient this way? 这样正确/有效吗? Or is there a better way? 或者,还有更好的方法?

If you have a choice of technology then I would suggest using JAXB . 如果您选择技术,那么我建议您使用JAXB。

It will unmarshal the XML into Java Object ,here do the modifications to java Object and then Marshal the modified Java Object into new XML File. 它将把XML解组为Java Object,在此对Java Object进行修改,然后将修改后的Java Object编组为新的XML File。

It has little bit of learning curve but code will be readable and maintainable. 它几乎没有学习曲线,但是代码是可读和可维护的。

for Basic tutorial of JAXB please refer to URL 有关JAXB的基础教程,请参考URL

当我想用Java解析xml时,我使用了dom4j ,它非常有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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