How to send Jaxb XmlAttribute data without java do

2019-03-04 22:50发布

So I have the following issue when trying to build an xml from java class using jaxb. My first tag needs to be like this :

<Entity Type=‘test-instance’>
Some xml
</Entity>

I need the first tag to have something written in it but the closing one needs to have only Entity.

I created a claas and added @XMLRootElement tag with name=Entity and using this I have the correct last tag. If I use the whole expression I have in both first and closing tag which does not help me.

I added a String variable with @XMLAttribute so I can add something else after Entity. The problem is if I initialize the variable with value, I will get the String double quotes. For example

@XMLAttribute(name=“Type”)
String x = “test-instance”;

When I build this it will read :

<Entity Type=“test-instance”>

, with double quotes and I need only single quotes.

If use the whole description I need in the xml attribute, for example :

@XMLAttribute(name=“Type=‘test-instance’”)
String x;

This will work fine but if the variable is not initialized then it won’t add anything and if write something like String x=“”; Then I will get :

<Entity Type=‘test-instance’=“”>

So I cannot get rid of the quotes which are coming from my String.

I was thinking something to either hardcode the first Entity tag and to have the last one where I close it different but couldn’t find anything.

Or the other option to set the XMLAttribute even if the String is not initialized.I saw something on the XMLElement that had something like “required” but it’s not available for XMLAttribute and I’m not really sure it does what I need it to.

Any help would be gratefully appreciated.

Thanks

1条回答
\"骚年 ilove
2楼-- · 2019-03-04 23:18

In XML applications the principle should be:

(a) Receiving applications shouldn't care about the insignificant lexical detail of how the XML is written. (The best way of achieving this is to use a respectable XML parser to read the XML.)

(b) Writing applications should be free to use whatever lexical conventions they find convenient. (Which means you can use any respectable serialization library to write the XML.)

The choice of single or double quotes for attributes is one of these insignificant lexical details.

We see a LOT of problems on StackOverflow caused by people not following these rules.

You haven't explained WHY you need to generate single quotes. Perhaps the XML is being consumed by an application that doesn't follow rule (a). In that case you should fix it! If you can't fix it, then you are vastly increasing your costs, in fact, there's very little point in using XML at all.

Sometimes when we ask this question we get the answer "because by client insists on it being that way". It's our job as professionals to educate our clients: they're paying the bills and it's irresponsible to spend their money on bad engineering even if that's what they said they wanted.

查看更多
登录 后发表回答