简体   繁体   English

在核心 Java - 从多个文件夹中读取多个 XML 文件和 append 在一个 Z3501BB093D36CFED30FB87 文件中

[英]In Core Java - Read Multiple XML Files form Multiple Folders and append in One XML file

  1. This is My main Driectory Path: C:\JavaPractice\Task3\Process\test\这是我的主要指令路径:C:\JavaPractice\Task3\Process\test\
  2. In the above main directory I have multiple subfolders and each subfolder contains a "tud.xml".在上面的主目录中,我有多个子文件夹,每个子文件夹都包含一个“tud.xml”。
  3. Need to crawl each tud.xml and extract the "< deg >" tag from that XML file.需要抓取每个 tud.xml 并从该 XML 文件中提取“< deg >”标签。
  4. if < deg > tag contains more than one degree (ex: < deg >MSC, PHD< /deg >) then split each degree into separate line.如果 < deg > 标签包含多个度数(例如:< deg >MSC, PHD< /deg >),则将每个度数拆分为单独的行。
  5. Append it in a single output file called deg.xml and unique and sort. Append 它在一个名为 deg.xml 的单个 output 文件中且唯一和排序。 (please note that output file does not contain duplicate words) (请注意output文件不包含重复字)

My Code:我的代码:

    import net.sf.saxon.Configuration;
    import net.sf.saxon.lib.NamespaceConstant;
    import net.sf.saxon.om.NodeInfo;
    import net.sf.saxon.om.TreeInfo;
    import net.sf.saxon.xpath.XPathFactoryImpl;
    import org.xml.sax.InputSource;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.xpath.*;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Scanner;
    import java.util.TreeMap;


    public class Task3 {

        private static String[] ParaToSentenc(String PtS) {
            String[] strArray = PtS.split(",");
            return strArray;
        }


        private static List<String> UniqueAndSortWord(String[] UW) {
            List<String> unique_sort = new ArrayList<String>();
            Map<String, String> hMap = new HashMap<String, String>();
            for(String word : UW) {
                if(!hMap.containsKey(word)) { 
                    hMap.put(word,"");
                    unique_sort.add(word);
                }        
            }
            Collections.sort(unique_sort);
            return unique_sort;
        }

        private static void FileWriter(String content, String outputfile) {
            File file = new File(outputfile);
            FileWriter writer = null;
            BufferedWriter bw = null;
            try {
                writer = new FileWriter(file);
                bw = new BufferedWriter(writer);
                bw.write(content);
                bw.flush();
                bw.close();
            }
            catch (IOException e) {
                System.out.println("Error");;
            }
        }       

        public static void main (String args[]) throws Exception {
            String Inputname = args[0];//sc.nextLine(); //"D:\\document.xml";
            String outputname = args[1];//sc.nextLine(); //"D:\\document.txt";
            Task3.runApp(Inputname, outputname);
            System.out.println("Success");
        }

        /**
         * Run the application
         */


        private static void runApp(String filename, String outputfile) throws Exception {


            /////////////////////////////////////////////
            // The following initialization code is specific to Saxon
            // Please refer to SaxonHE documentation for details
            System.setProperty("javax.xml.xpath.XPathFactory:"+
                               NamespaceConstant.OBJECT_MODEL_SAXON,
                               "net.sf.saxon.xpath.XPathFactoryImpl");

            XPathFactory xpFactory = XPathFactory.
                                     newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
            XPath xpExpression = xpFactory.newXPath();
            System.err.println("Loaded XPath Provider " + xpExpression.getClass().getName());

            // Build the source document.
            InputSource inputSrc = new InputSource(new File(filename).toURL().toString());
            SAXSource saxSrc = new SAXSource(inputSrc);
            Configuration config = ((XPathFactoryImpl) xpFactory).getConfiguration();
            TreeInfo treeInfo = config.buildDocumentTree(saxSrc);
            // End Saxon specific code
            /////////////////////////////////////////////


            XPathExpression findwtTags =
                                        xpExpression.compile("count(//deg)");


            Number countResults = (Number)findwtTags.evaluate(treeInfo, XPathConstants.NUMBER);


            // Get a list of the <deg> Tags
            // The following expression gets a set of nodes that have a <deg> Tags,
            // then extracts the text node from the <deg> tags
            XPathExpression findwtTextNodes =
                                             xpExpression.compile("//deg");



            //global string

            String global = "";

            List resultNodeList = (List) findwtTextNodes.evaluate(treeInfo, XPathConstants.NODESET);
            if (resultNodeList != null) {
                int count = resultNodeList.size();

                for (int i = 0; i < count; i++) {
                    NodeInfo cNode = (NodeInfo) resultNodeList.get(i);
                    String name = cNode.getStringValue();
                    global = global + "\n" + name;
                }
            }


            //Full content text...
            String globalText = "Full Degree content:" + global + "\n\n";


            // Para To Sentence...
            String[] strSenArray = ParaToSentenc(global);
            globalText = globalText + "Each Degree separated in line by line:\n";
    //        globalText = globalText + "Sentence Count : "+strSenArray.length+"\n";
            for(int i=0; i<strSenArray.length; i++){
                globalText = globalText + strSenArray[i].trim() + "\n";
            }
            globalText = globalText + "\n";



            //Unique Words
            List<String> strUniqueList = UniqueAndSortWord(strSenArray);
            globalText = globalText + "Unique Degree list:\n";
            for(String word : strUniqueList){
                globalText = globalText + word.trim() + "\n";
            }
            globalText = globalText.substring(0, globalText.length()-1);
            globalText = globalText + "\n\n";

            //All Text wtite into file...
            FileWriter(globalText, outputfile);
        }



    }

You can do this all in one XPath expression with XPath 3.1:您可以使用 XPath 3.1 在一个 XPath 表达式中完成所有操作:

(collection('file:///C:/JavaPractice/Task3/Process/test?select=tud.xml;recurse=yes') //deg 
! tokenize(., ',')) => distinct-values() => sort())))

All the Java needs to do is run this expression and process the resulting sequence of strings. Java 需要做的就是运行这个表达式并处理生成的字符串序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM