package com.cslg.ppa.service.commom;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
public class XmlParseService {
    public List<String> xmlParse(String xmlData, String str) {
        List<String> reStrs = new ArrayList<>();
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource src = new InputSource(new StringReader(xmlData));
            Document doc = builder.parse(src);
            NodeList recordList = doc.getElementsByTagName(str);
            for (int i = 0; i < recordList.getLength(); i++) {
                Node recordNode = recordList.item(i);
                if (recordNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) recordNode;
                    reStrs.add(element.getTextContent());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reStrs;
    }
}
