Xml element ordering and attributes-vs-elements

38 views
Skip to first unread message

Rich MacDonald

unread,
Jan 19, 2025, 4:58:04 PMJan 19
to jackson-user
I came across a question on stack overflow at https://stackoverflow.com/questions/71257905/how-to-serialize-map-field-as-xml-attributes-with-jackson-mapper that I knew the answer to. So I wrote some test code to demonstrate it and I notice that the xml element order was "not right". Random maybe, or alphabetical? So I added a JsonPropertyOrder annotation and discovered that the XmlMapper does not respect it. Code shown below:

```
 @JsonPropertyOrder(value = {"name", "params"})
static class DataItem {

public String name;

@JacksonXmlProperty(isAttribute = true)
public Map params = new HashMap<>();

public static void main(String[] args) throws JsonProcessingException {
DataItem data1 = new DataItem();
data1.name = "some name";
data1.params.put("p1", "one");
data1.params.put("p2", "two");
XmlMapper xmlMapper = new XmlMapper();
String xmlString = xmlMapper.writeValueAsString(data1);
System.out.println(xmlString);

// Result is:  <DataItem><params p1="one" p2="two"/><name>some name</name></DataItem>

// <DataItem>
//     <params p1="one" p2="two"/>
//     <name>some name</name>
    // </DataItem>
}
}
```

Is this a mistake in my code and/or is there another way to order the xml elements?

I was led to this forum question because I am trying to do the same thing except put the attributes on the parent element, not create a child element. I want the xml to look like this:

```
<DataItem p1="one" p2="two">
 <name>some name</name>
</DataItem>
```

I tried adding `@JacksonXmlProperty(isAttribute = true)` to the params field but no luck. Any tips?

Apologies if this is answered somewhere else in the forum. I looked but did not find.

Rich MacDonald
Message has been deleted
Message has been deleted
Message has been deleted

陳裕仁(Alan)

unread,
Mar 2, 2025, 1:33:06 PMMar 2
to jackson-user
你們好我目前失業了我需要工作的,請問有人可以幫我嗎

Rich MacDonald 在 2025年1月20日 星期一清晨5:58:04 [UTC+8] 的信中寫道:
Reply all
Reply to author
Forward
0 new messages