当前位置: 首页 > 知识库问答 >
问题:

解析XML文件.如何保存到数据库

韦俊英
2023-03-14

XML

<?xml version="1.0" standalone="yes"?>
<sdnList>
  <sdnEntry>
    <uid>1</uid>
    <lastName>AAAAAAAA</lastName>
    <sdnType>Entity</sdnType>
    <programList>
      <program>UID</program>
    </programList>
    <akaList>
      <aka>
        <uid>12</uid>
        <type>a.k.a.</type>      
        <lastName>ABCD</lastName>
      </aka>
    </akaList>
    <addressList>
      <address>
        <uid>25</uid>
        <city>City</city>
        <country>Country</country>
      </address>
    </addressList>
  </sdnEntry>
  <sdnEntry>
    <uid>2</uid>
    <lastName>BBBBBB</lastName>
    <sdnType>Entity</sdnType>
    <programList>
      <program>UID</program>
    </programList>
    <akaList>
      <aka>
        <uid>219</uid>
        <type>a.k.a.</type>
        <category>weak</category>
        <lastName>BCC</lastName>
      </aka>
      <aka>
        <uid>220</uid>
        <type>a.k.a.</type>
        <category>strong</category>
        <lastName>ABABAB</lastName>
      </aka>
    </akaList>
    <addressList>
      <address>
        <uid>199</uid>
        <address1>Address</address1>
        <city>City</city>
        <postalCode>CODE</postalCode>
        <country>Country</country>
      </address>
      <address>
        <uid>200</uid>
        <address1>Address</address1>
        <city>City</city>
        <postalCode>CODE</postalCode>
        <country>Country</country>
      </address>
      <address>
        <uid>201</uid>
        <address1>Address</address1>
        <city>City</city>
        <postalCode>CODE</postalCode>
        <country>Country</country>
      </address>
    </addressList>
  </sdnEntry>
  <sdnEntry>
    <uid>3</uid>
    <lastName>CCCCCCC</lastName>
    <sdnType>Entity</sdnType>
    <programList>
      <program>UID</program>
    </programList>
    <addressList>
      <address>
        <uid>247</uid>
        <address1>Address</address1>
        <city>City</city>
        <country>Country</country>
      </address>
    </addressList>
  </sdnEntry>
</sdnList>

服务

@Service
public class UploadURLServiceImpl implements UploadURLService {

    @Autowired
    private final FileDTORepository fileDTORepository;

    @Autowired
    public UploadURLServiceImpl(FileDTORepository fileDTORepository) {
        this.fileDTORepository = fileDTORepository;
    }

    @Override
    public boolean uploadData(String url) {
        try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());
             FileOutputStream fileOutputStream = new FileOutputStream(new File("sdn.xml"))) {
            byte dataBuffer[] = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
                fileOutputStream.write(dataBuffer, 0, bytesRead);
            }
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    @Override
    public void parseSdnFile(String fileName) throws ParserConfigurationException, IOException, SAXException{

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

      // try {
           // dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

            DocumentBuilder db = dbf.newDocumentBuilder();

            Document doc = db.parse(new File(fileName));

            doc.getDocumentElement().normalize();

            //Element docEl = doc.getDocumentElement();

            NodeList list = doc.getElementsByTagName("sdnEntry");

            List<SdnEntryDTO> ofacs = new ArrayList<>();

            for (int temp = 0; temp < list.getLength(); temp++) {
                    Node node = list.item(temp);

                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                            Element element = (Element) node;

                            String id = element.getElementsByTagName("uid").item(0).getTextContent();
                            String uid = element.getElementsByTagName("uid").item(0).getTextContent();
                            String lastName = element.getElementsByTagName("lastName").item(0).getTextContent();
                            String firstName = "";
                            if ((element.getElementsByTagName("firstName") != null)
                                    && (element.getElementsByTagName("firstName").item(0) != null)) {
                                firstName = element.getElementsByTagName("firstName").item(0).getTextContent();
                            }
                            String program = element.getElementsByTagName("program").item(0).getTextContent();
                            String sdnType = element.getElementsByTagName("sdnType").item(0).getTextContent();

                            //--------------alias

                        List<String> akaList = new ArrayList<>();
                        if (element.getElementsByTagName("akaList") != null && element.getElementsByTagName("akaList").getLength() > 0
                                && ((Element) element.getElementsByTagName("akaList").item(0)).getElementsByTagName("aka") != null) {
                            Node c = element.getElementsByTagName("akaList").item(0);
                            NodeList akaNodeList = ((Element) c).getElementsByTagName("aka");

                            if (akaNodeList != null) {
                                for (int i = 0; i < akaNodeList.getLength(); i++) {
                                    Node akaNode = akaNodeList.item(i);
                                    if (akaNode.getNodeType() == Node.ELEMENT_NODE) {
                                        Element aka = (Element) akaNode;

                                        if (aka.getElementsByTagName("firstName") != null && aka.getElementsByTagName("firstName").getLength() > 0) {
                                            akaList.add(aka.getElementsByTagName("firstName").item(0).getTextContent());
                                        }

                                        if (aka.getElementsByTagName("lastName") != null && aka.getElementsByTagName("lastName").getLength() > 0) {
                                            akaList.add(aka.getElementsByTagName("lastName").item(0).getTextContent());
                                        }
                                    }
                                }
                            }
                        }
                        if (akaList.size() > 0) {

                            SdnEntryDTO sdnEntryDTO = new SdnEntryDTO(Long.parseLong(uid),
                                    firstName + " " + lastName, program, sdnType, Collections.singletonList(String.join(",", akaList)));

                            ofacs.add(sdnEntryDTO);
                        }
                        }
                    }

                for (SdnEntryDTO sdnEntryDTO : ofacs) {
                    fileDTORepository.saveAll(ofacs);
                }
//        } catch (ParserConfigurationException | SAXException | IOException e) {
//            e.printStackTrace();
//        }
    }
}

实体

@Entity
@Table(name = "customer")
public class SdnEntryDTO {

    @Id
    @GeneratedValue(generator = "uuid")
    private Long id;

    @Column(name = "ofac_id")
    private Long uid;

    @Column(name = "fullName", length = 255)
    private String fullName;

    @Column(name = "program", length = 50)
    private String program;

    @Column(name = "type", length = 50)
    private String sdnType;

    @Column(name = "alias", length = 255)
    private List<String> akaList;

    public SdnEntryDTO() {
    }

    public SdnEntryDTO(Long uid, String fullName, String program, String sdnType, List<String> akaList) {
        this.uid = uid;
        this.fullName = fullName;
        this.program = program;
        this.sdnType = sdnType;
        this.akaList = akaList;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getUid() {
        return uid;
    }

    public void setUid(Long uid) {
        this.uid = uid;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public String getProgram() {
        return program;
    }

    public void setProgram(String program) {
        this.program = program;
    }

    public String getSdnType() {
        return sdnType;
    }

    public void setSdnType(String sdnType) {
        this.sdnType = sdnType;
    }

    public List<String> getAkaList() {
        return akaList;
    }

    public void setAkaList(List<String> akaList) {
        this.akaList = akaList;
    }
}

存储库

@Repository
public interface FileDTORepository extends JpaRepository<SdnEntryDTO, Long> {
}

我有一个错误:

创建在类路径资源[org/springframework/boot/autoconfigure/orm/jpa/hibernatejbaconfiguration.class]中定义的名为“entityManagerFactory”的bean时出错:初始化方法调用失败;嵌套的异常是javax。坚持不懈PersistenceException:[PersistenceUnit:default]无法构建Hibernate SessionFactory;嵌套的异常是org。冬眠MappingException:无法确定java的类型。util。列:[org.hibernate.mapping.Column(别名)]

有什么想法吗?

共有1个答案

葛雨华
2023-03-14

下面的for-loop而不是你的应该做这项工作,但我完全不建议你这么做。这是一段很难读懂的代码。请考虑使用其他XML解析库,如JAXB(https://www.baeldung.com/java-xml-libraries).

for (int temp = 0; temp < list.getLength(); temp++) {
    Node node = list.item(temp);
    System.out.println("");

    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;

        System.out.println("uid : " + element.getElementsByTagName("uid").item(0).getTextContent());
        if ((element.getElementsByTagName("firstName") != null)
                && (element.getElementsByTagName("firstName").item(0) != null)) {
            System.out.println("fullName : " + (element.getElementsByTagName("lastName").item(0).getTextContent())
                    + " " + (element.getElementsByTagName("firstName").item(0).getTextContent()));
        } else {
            System.out.println("fullName : " + element.getElementsByTagName("lastName").item(0).getTextContent());
        }
        System.out.println("program : " + element.getElementsByTagName("program").item(0).getTextContent());
        System.out.println("sdnType : " + element.getElementsByTagName("sdnType").item(0).getTextContent());

        List<String> akaList = new ArrayList<>();
        if (element.getElementsByTagName("akaList") != null && element.getElementsByTagName("akaList").getLength() > 0
                && ((Element) element.getElementsByTagName("akaList").item(0)).getElementsByTagName("aka") != null) {
            Node c = element.getElementsByTagName("akaList").item(0);
            NodeList akaNodeList = ((Element) c).getElementsByTagName("aka");

            if (akaNodeList != null) {
                for (int i = 0; i < akaNodeList.getLength(); i++) {
                    Node akaNode = akaNodeList.item(i);
                    if (akaNode.getNodeType() == Node.ELEMENT_NODE) {
                        Element aka = (Element) akaNode;

                        if (aka.getElementsByTagName("firstName") != null && aka.getElementsByTagName("firstName").getLength() > 0) {
                            akaList.add(aka.getElementsByTagName("firstName").item(0).getTextContent());
                        }

                        if (aka.getElementsByTagName("lastName") != null && aka.getElementsByTagName("lastName").getLength() > 0) {
                            akaList.add(aka.getElementsByTagName("lastName").item(0).getTextContent());
                        }
                    }
                }
            }
        }

        if (akaList.size() > 0) {
            System.out.println("alias : " + String.join(",", akaList));
        }
    }
}

更新日期:2021年9月6日

使用@ElementCollection而不是@Colzo(name="alias",长度=255)。您将其定义为List,因此@ColementCollection不起作用,因为HiberNate不知道如何处理List@ElementCollection通过处理基本类型或可嵌入类的实例集合来实现这一点。查看本文了解更多详细信息。

更新日期:2021年7月9日

列表的转换

@Column(name = "alias", length = 255)
@Convert(converter = ListToStringConverter.class)
private List<String> akaList;

现在,您需要实现ListToStringConver,如下所示:

@Converter
public class ListToStringConverter implements AttributeConverter<List<String>, String>{
    @Override
    public String convertToDatabaseColumn(List<String> attribute) {
        return attribute == null ? null : StringUtils.join(attribute,",");
    }

    @Override
    public List<String> convertToEntityAttribute(String dbData) {
        if (StringUtils.isBlank(dbData))
            return Collections.emptyList();

        try (Stream<String> stream = Arrays.stream(dbData.split(","))) {
            return stream.collect(Collectors.toList());
        }
    }
}

 类似资料:
  • 我试着把XML解析成R数据帧,这个链接帮了我大忙: 如何从xml文件创建R数据帧 但我还是没有弄清楚我的问题: 下面是我的代码: 我想要的数据帧是这样的: 我被困住了,任何帮助都将非常感谢,谢谢。

  • 问题内容: 我有这个项目: 导入文件 连接到SQL Server数据库 将所有数据转移到数据库中 文本文件按选项卡划分为四个字段,例如数据库。 我已经完成了使用富文本框并将所有数据保存在字符串中的第一步。我的想法是将字符串拆分为每行并将其保存在数组中,然后:如何拆分每一行,以便可以正确保存字段?如何将SQL Server上的数据库连接到C#上的项目? 问题答案: 让我们一次解决这一步骤… 获取数据

  • 本文向大家介绍C#从数据库读取数据到DataSet并保存到xml文件的方法,包括了C#从数据库读取数据到DataSet并保存到xml文件的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了C#从数据库读取数据到DataSet并保存到xml文件的方法。分享给大家供大家参考。具体实现方法如下: DataSet有一个WriteXml方法可以直接将数据保存到xml文件 希望本文所述对大家的C#程

  • 问题内容: 我有xml文件。我需要阅读它,进行一些更改并将新的更改版本写入一些新的目的地。 我设法读取,分析和修补这个文件(,,等)。 但是我找不到一种方法来保存该文件。有没有办法获得纯文本视图(如)或其他更好的方法? 问题答案: 像这样的作品:

  • 本文向大家介绍java如何解析/读取xml文件,包括了java如何解析/读取xml文件的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了java解析/读取xml文件的方法,供大家参考,具体内容如下 XML文件 Java 代码: 以上就是本文的全部内容,希望对大家的学习有所帮助。

  • 我有一个XML文件,如 我需要值,即“OEBPS/content.opf”文本。我尝试使用文档生成器和XML解析器,但没有结果。如何遍历该节点并获取值