问题
I try to serialize some config classes to xml config files using the XMLMapper. but I have some trouble with the attribute generation. Actually the generated XML is perfect, but XMLMapper adds sometimes a prefix to my attribute names.
e.g.
<Config zdef-2031720317:value="0">
instead of
<Config value="0">
This is really bad because i can't process the xml Structure afterwards with XOM anymore :(
Where is this effect coming from? I found already the fact that the xml generator seems to auto fix the namespace to make the attributes unique. Why is this necessary and how can i avoid it?
回答1:
One thing that has often caused problems with XmlMapper
is underlying XML Stax library -- one included in JDK sometimes adds unnecessary namespace prefixes.
The solution is to use Woodstox Stax implementation instead, as it is known to work better in general, and also in this specific case.
If you use Maven, you can just add this in your pom.xml
:
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
<version>4.1.4</version>
</dependency>
and your problem may be solved. As an added bonus, this is faster XML parser as well.
回答2:
For those who are looking for a non woodstox answer. This did the trick for me:
xmlMapper.getFactory().getXMLOutputFactory().setProperty("javax.xml.stream.isRepairingNamespaces", false);
来源:https://stackoverflow.com/questions/14818134/xmlwriter-extends-attribute-name-with-zdef