如何在反序列化 xml 时允许使用 jackson 重复键

how to allow duplicate keys with jackson while deserializing xml

我有一个简单的 xml 文件,结构如下,包含多个 B

<?xml version="1.0" encoding="UTF-8"?>
<Example>
   <ExampleId>0000</ExampleId>
   <Name>test</Name>
   <Important1>
      <Id>
         <Number>1111111111</Number>
      </Id>
   </Important1>
   <B>
      <Name>test2</Name>
      <Important2>
         <Id>
            <Number>2222222222</Number>
         </Id>
      </Important2>
   </B>
   <B>
      <Name>test3</Name>
      <Important2>
         <Id>
            <Number>3333333333</Number>
         </Id>
      </Important2>
   </B>
</Example>

我需要从 Number 键中检索所有值到 List
我尝试了多种方法

JsonNode numberParser = xmlMapper.readTree(inputStream);
JsonNode node1 = numberParser.get("Example");
            
//first try
List<String> list =node1.findValuesAsText("Number");
            
//second try
List<String> list =new ArrayList<String>();
node1.fields().forEachRemaining(firstEntry -> {
    if(firstEntry.getKey().equals("Important1")){
            JsonNode fieldsNode = firstEntry.getValue();
            String numberFromImportant1 = fieldsNode.findValue("Number").asText();
            list.add(numberFromImportant1);
    }
    if(firstEntry.getKey().equals("B")){
            JsonNode fieldsNode = firstEntry.getValue();
            String numberFromImportant2 = fieldsNode.findValue("Number").asText();
            list.add(numberFromImportant2);
    }
});

但是,如果 jackson 在反序列化时遇到重复的 B 节点,它似乎只从 Number 中获取最后一个值 有什么方法可以防止这种情况发生并允许 Jackson 也考虑重复项吗?

如果您只想检索 node 数字的值,请考虑使用 xpath。将 double forward space 附加到 XML 节点将搜索该节点(在整个 xml 文件中)。例如://Number

例如:

Document xmlDocument = builder.parse(inputStream);
this.clean(xmlDocument);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "//Number";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);