验证 List(Jaxb) 中未编组的条目

Posted

技术标签:

【中文标题】验证 List(Jaxb) 中未编组的条目【英文标题】:Verifying unmarshalled entries from List( Jaxb) 【发布时间】:2021-11-05 06:28:57 【问题描述】:

我有 4 个 XML 文件,其结构如下:

<?xml version="1.0"?>
<Registry>
    <Insitutions>
        <Insitiution>
            <name>A</name>
            <location>B</location>
        </Insitiution>
        <Insitiution>
            <name>C</name>
            <location>D</location>
        </Insitiution>
        <Insitiution>
            <name>E</name>
            <location>F</location>
        </Insitiution>
    </Insitutions>
</Registry>

我已经为各个 XML 标记编写了类,并使用 jaxb 将它们解组。 我解组所有文件并将所有条目存储在一个列表中,如下所示:

  private static List<String> loadBaseNodesets() throws JAXBException 
        log.info("Loading nodesets");
        Registry xmlentries = null;
        JAXBContext jaxbContext = null;
        List<Registry> entries = new ArrayList<>();
        List<String> privateBaseNodeSets= new ArrayList<>();
        File dir = new File("XMLFiles");
        if (dir.exists() && dir.isDirectory()) 
            FileFilter filter = new FileFilter() 
                public boolean accept(File file) 
                    return file.isFile() && file.getName().endsWith(".xml");
                
            ;
        log.info("iterating through all files");
        File [] files = dir.listFiles(filter);
        if (files != null)                     
                for (int i =0;i <1;i++)    
                    jaxbContext = JAXBContext.newInstance(Registry.class);
                    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                    xmlentries = (Registry) jaxbUnmarshaller.unmarshal(files[i]);
                    privateBaseNodeSets.add(xmlentries.toString());
                    log.info(files[i].getName()+" NodeSet loaded");
                    entries.add(xmlentries);            
                
            
        
               
        log.info("Nodeset loading complete");
    return privateBaseNodeSets;
  

我需要将所有 xmlentries 放到一个字符串列表中。

现在从主程序中,我想检查是否可以获得相同格式的 XML 条目。

 public static void main(String[] args) throws JAXBException 
    log.info("Started local test main");
    List<String> baseNodesets = loadBaseNodesets();
    ListIterator<String> litr = baseNodesets.listIterator();
    while (litr.hasNext()) 
        
        JAXBContext jaxbContext=JAXBContext.newInstance(Registry.class);
        Marshaller marshaller = jaxbContext.createMarshaller();#
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(, System.out);// DONT KNOW THE FIRST PARAMETER
        

我无法在此处获取第一个参数。有人可以帮忙吗?

【问题讨论】:

答案对您有帮助吗?能否解决问题? 当然做到了!抱歉有点耽误了。再次感谢:) 【参考方案1】:

您的方法marshal 需要一个java 对象作为第一个参数转换为XML。

这会将您的条目列表转换为 xml 列表。

    final JAXBContext jaxbContext=JAXBContext.newInstance(Registry.class);
    final Marshaller marshaller = jaxbContext.createMarshaller();
    List<String> xmlEntries = entries.stream().map(entrie -> 
      OutputStream os = new ByteArrayOutputStream();
      marshaller.marshal(entrie, os); <-- your object to transform to XML
      return os.toString();
    .collect(Collectors.toList());

【讨论】:

【参考方案2】:

我不确定我是否正确理解了你的问题,但我猜你正在尝试做这样的事情:

    逐个读取每个文件并解组并存储在entries列表中。 然后循环遍历entries List 并一一编组。 将转换后的 XML 存储到 List 中

我在一个文件夹中存储了 2 个相同的 XML 文件并尝试读取它

XML 文件:

<?xml version="1.0"?>
<Registry>
    <Insitutions>
        <Insitiution>
            <name>A</name>
            <location>B</location>
        </Insitiution>
        <Insitiution>
            <name>C</name>
            <location>D</location>
        </Insitiution>
        <Insitiution>
            <name>E</name>
            <location>F</location>
        </Insitiution>
    </Insitutions>
</Registry>

根:

@Data
@XmlRootElement(name = "Registry")
@XmlAccessorType(XmlAccessType.FIELD)
public class Root 
    @XmlElementWrapper(name = "Insitutions")
    @XmlElement(name = "Insitiution")
    private List<Insitiution> Insitiution;

机构:

@Data
@XmlAccessorType(XmlAccessType.FIELD)
public class Insitiution 
    private String name;
    private String location;

编组(主要):

public class Marshalling 

    public static void main(String[] args) throws JAXBException, XMLStreamException, FactoryConfigurationError, IOException, SAXException 
        final File dir = new File("/Users/Downloads/test");
        final List<Root> entries = new ArrayList<>();
        final Unmarshaller unmarshaller = JAXBContext.newInstance(com.newJAXB.Root.class).createUnmarshaller();
        final StringWriter singleXmlEvent = new StringWriter();
        final List<String> xmlOutput = new ArrayList<>();
        final Marshaller marshaller = JAXBContext.newInstance(Root.class).createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        for (File file : dir.listFiles()) 
            if (!file.isDirectory() && file.getName().endsWith(".xml")) 
                //Storing all the files into entries List
                final DataInputStream inputStream = new DataInputStream(new FileInputStream(file.getAbsolutePath()));
                final XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
                final com.newJAXB.Root root = unmarshaller.unmarshal(xmlStreamReader, com.newJAXB.Root.class).getValue();
                entries.add(root);
                System.out.println(root.toString());
            
        

        //Loop through each entry in entries and marshal it
        for (Root item : entries) 
            marshaller.marshal(item, singleXmlEvent);
            xmlOutput.add(singleXmlEvent.toString());
            // Clear the StringWriter for next event
            singleXmlEvent.getBuffer().setLength(0);
        

        //Final all the XML
        System.out.println(xmlOutput);
    

输出:

Root(Insitiution=[Insitiution(name=A, location=B), Insitiution(name=C, location=D), Insitiution(name=E, location=F)])
Root(Insitiution=[Insitiution(name=A, location=B), Insitiution(name=C, location=D), Insitiution(name=E, location=F)])
[<?xml version="1.0" encoding="UTF-8"?>
<Registry>
   <Insitutions>
      <Insitiution>
         <name>A</name>
         <location>B</location>
      </Insitiution>
      <Insitiution>
         <name>C</name>
         <location>D</location>
      </Insitiution>
      <Insitiution>
         <name>E</name>
         <location>F</location>
      </Insitiution>
   </Insitutions>
</Registry>
, <?xml version="1.0" encoding="UTF-8"?>
<Registry>
   <Insitutions>
      <Insitiution>
         <name>A</name>
         <location>B</location>
      </Insitiution>
      <Insitiution>
         <name>C</name>
         <location>D</location>
      </Insitiution>
      <Insitiution>
         <name>E</name>
         <location>F</location>
      </Insitiution>
   </Insitutions>
</Registry>
]

【讨论】:

以上是关于验证 List(Jaxb) 中未编组的条目的主要内容,如果未能解决你的问题,请参考以下文章

来自JaxB类的DTD验证

JAXB:如何编组列表中的对象?

无法将类型编组为元素,因为它缺少自动生成的类的@XmlRootElement注释

JAXB XMLAdapter 方法不抛出异常

使用带有签名、加密和编码的 JAXB

自定义 jaxb 编组输出