使用SimpleXML的XML声明标记

使用SimpleXML的XML声明标记

本文介绍了使用SimpleXML的XML声明标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我开始使用带注释的Simple XML框架(链接)对于Java,但我不知道,如何排除XML声明标记<?xml version =1.0encoding =UTF-8?> 在XML文件中。所以我的问题是:如何将XML声明作为第一个标记?

I'm starting to use the Simple XML framework with annotations (link) for Java, but I don't get, how to prelude the XML declaration tag <?xml version="1.0" encoding="UTF-8" ?> in the XML file. So my question is: How do I get the XML declaration as first tag?

package simplexml;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root
public class Example {

    @Element
    private String text;

    @Attribute
    private int index;

    public Example(String text, int index) {
        this.text = text;
        this.index = index;
    }

    public String getMessage() {
        return text;
    }

    public int getId() {
        return index;
    }
}

测试:

public static void main(String[] args) {
        Serializer serializer = new Persister();
        Example example = new Example("Example message", 123);
        File result = new File("example.xml");

        try {
            serializer.write(example, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

产生:

<example index="123">
   <text>Example message</text>
</example>

我想要的是:

<?xml version="1.0" encoding="UTF-8" ?>
<example index="123">
   <text>Example message</text>
</example>

谢谢!另外,我在哪里可以查看这些内容?

Thanks! Also, where could I look such things up?

推荐答案

我使用Spring for Android发送XML请求,并且面临同样的问题问题。以下是基于@ implicit_knowledge解决方案使其工作的代码,以防任何人需要它。

I use Spring for Android to send XML requests, and was facing the same problem. Here's the code to get it work based on @implicit_knowledge's solution in case anyone needs it.

RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
Serializer serializer = new Persister(new Format("<?xml version=\"1.0\" encoding= \"UTF-8\" ?>"));
restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter(serializer));
restTemplate.postForObject(URL, udata, String.class);

这篇关于使用SimpleXML的XML声明标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 00:35