【问题标题】:Parse XML file. How to save into database解析 XML 文件。如何存入数据库
【发布时间】:2021-11-02 18:13:28
【问题描述】:

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> {
}

我有一个错误:

在类中定义名称为“entityManagerFactory”的 bean 创建错误 路径资源 [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: 调用 init 方法失败;嵌套异常是 javax.persistence.PersistenceException:[PersistenceUnit:默认] 无法构建 Hibernate SessionFactory;嵌套异常是 org.hibernate.MappingException:无法确定类型: java.util.List,在表:客户,列: [org.hibernate.mapping.Column(别名)]

有什么想法吗?

【问题讨论】:

  • 我会改写我的问题。输出应该是:uid: some data fullName: some data program: some data sdnType: some data alias: lastName and fullName from akaList 应该在这里
  • 您能否编辑您的问题,以便更清楚您在寻找什么?谢谢。
  • 我想显示如下数据:fullName = (firstName + lastName), uid, program, sdnType and alias = (fistName + lastName, 属于akaList标签)
  • 如果我添加这样的代码: if ((element.getElementsByTagName("akaList") != null) && (element.getElementsByTagName("akaList").item(0) != null)) { System.out.println("别名:" + element.getElementsByTagName("akaList").item(0).getTextContent())); } else { System.out.println("别名:" + " ");}
  • 我有:uid:1 fullName:AAAAAAAAA 程序:UID sdnType:实体别名:12 a.k.a. ABCD

标签: java xml spring


【解决方案1】:

下面的 for 循环而不是你的应该可以完成这项工作,但我完全不建议你这样做。这是非常难以阅读的代码。请考虑使用其他 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 年 6 月 9 日更新

使用@ElementCollection 代替@Column(name = "alias", length = 255)。您将其定义为List,因此@Column 不起作用,因为Hibernate 不知道如何处理List@ElementCollection 通过处理基本类型或可嵌入类的实例集合来做到这一点。查看this文章了解更多详情。


2021 年 7 月 9 日更新

List&lt;String&gt;到数据库中单列的转换可以实现如下:

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

现在你需要实现ListToStringConverter,如下:

@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());
        }
    }
}

【讨论】:

  • 输出这部分代码的错误: element.getElementsByTagName("akaList")./getElementsByTagName/("aka"), if (/getElementsByTagName/("firstName") != null) {
  • 还有这个:NodeList akaNodeList = element.getElementsByTagName("akaList")./getElementsByTagName/("aka");
  • 我已经更新了我的答案。现在好了,请检查一下;)
  • 唯一的事情是,当我将这段代码插入我的应用程序时,我收到一个错误:在类路径资源 [org/springframework/boot/autoconfigure/orm/ jpa / HibernateJpaConfiguration.class]:init方法的调用失败;嵌套异常是 javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory;嵌套异常是 org.hibernate.MappingException:无法确定类型:java.util.List,表:客户,列:[org.hibernate.mapping.Column(别名)]
  • 您对此有什么想法吗?)
猜你喜欢
  • 2012-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
相关资源
最近更新 更多