Groovy:如何将文本响应解析为xml Document

时间:2017-10-14 17:05:33

标签: java groovy apache-nifi

我想从文件夹中读取xml文件,我想更新它并制作新的流文件(我的代码将放在nifi处理器中),这将包含这些更新的数据,我得到了例外lilke这个:

引起:javax.script.ScriptException:javax.script.ScriptException:org.xml.sax.SAXParseException; lineNumber:1; columnNumber:1; prolog中不允许使用内容。

  

在   org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:159)     在   javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)     在   org.apache.nifi.script.impl.GroovyScriptEngineConfigurator.eval(GroovyScriptEngineConfigurator.java:54)     在   org.apache.nifi.processors.script.ExecuteScript.onTrigger(ExecuteScript.java:220)     ...省略了11个常见帧引起的:javax.script.ScriptException:   org.xml.sax.SAXParseException; lineNumber:1; columnNumber:1;内容   不允许在prolog中。在   org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:355)     在   org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:153)     ...省略了14个常见帧引起的:   org.xml.sax.SAXParseException:prolog中不允许使用内容。在   com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:257)     在   com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)     在javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121)     在javax.xml.parsers.DocumentBuilder $ parse.call(未知来源)at   Script13.run(Script13.groovy:54)at   org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:352)     ...省略了15个常见帧

1. 我应该更改什么?(除了使用doc = builder.parse(file)更改doc = builder.parse(inputStream),因为我需要使用字符串数据进行后续处理)

  1. 我无法完成任务的另一个原因是我无法生成我将放置所有更新的xml数据的流文件,由于某种原因我得到了空的流文件,即使我使用此doc = builder.parse(file)我的意思是使用配置文件phisically(文件文件=新文件('路径')),我应该改变什么来改善这种情况。
  2. 如果我使用字符串内容,我应该使用任何替代方法来获取xml标记数据,除了使用NodeList(我的意思是可以使用任何更好的用例)? 这是我的常规代码:
  3. import org.apache.commons.io.IOUtils;
    import java.nio.charset.StandardCharsets;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Node;
    import org.w3c.dom.Element;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import java.nio.channels.Channels;
    import java.nio.channels.FileLock;
    import javax.xml.xpath.*;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    
      File file = new File("C://Users//user//Desktop//2//conf.xml");
            String content = '';
    
    
    
    
            RandomAccessFile ini = new RandomAccessFile(file, "rws");
            FileLock lock = ini.getChannel().lock();
            BufferedReader s;
            DocumentBuilder dBuilder = null;
            Document doc=null;
            String start,startDate,endDate,runAs,makeVersion,patch;
            try {
                String sCurrentLine;
                s= new BufferedReader(Channels.newReader(ini.getChannel(), "UTF-8"));
    
    
                while ((sCurrentLine = s.readLine()) != null) {
                    content+=sCurrentLine;
                }
    
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                InputStream inputStream = new    ByteArrayInputStream(content.getBytes());
                doc = builder.parse(inputStream);
                NodeList nList = doc.getElementsByTagName("localAttributes");
                for (int temp = 0; temp < nList.getLength(); temp++) {
    
                    Node nNode = nList.item(temp);
    
    
                    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
    
                        Element eElement = (Element) nNode;
    
    
                        start = eElement.getElementsByTagName("start").item(0).getTextContent();
                        startDate = eElement.getElementsByTagName("startDate").item(0).getTextContent();
                        endDate = eElement.getElementsByTagName("endDate").item(0).getTextContent();
                        patch = eElement.getElementsByTagName("patch").item(0).getTextContent();
                        runAs = eElement.getElementsByTagName("runAs").item(0).getTextContent();
                        makeVersion = eElement.getElementsByTagName("makeVersion").item(0).getTextContent();
    
                    }
                }
              def flowFile1=session.create();
                flowFile1 = session.putAttribute(flowFile1, "start", start);
                flowFile1 = session.putAttribute(flowFile1, "startDate", startDate);
                flowFile1 = session.putAttribute(flowFile1, "endDate", endDate);
                flowFile1 = session.putAttribute(flowFile1, "runAs", runAs);
                flowFile1 = session.putAttribute(flowFile1, "patch", patch);
                flowFile1 = session.putAttribute(flowFile1, "makeVersion", makeVersion);
    
                flowFile1 = session.putAttribute(flowFile1, "filename", "conf.xml");
    
                Document xmlDocument = builder.parse(inputStream);
    
    
                XPathExpression myNodeList = (XPathExpression) xPath.compile("/localAttributes");
                Node nodeGettingChanged = (Node) myNodeList.evaluate(xmlDocument, XPathConstants.NODE);
                NodeList childNodes = nodeGettingChanged.getChildNodes();
                for (int i = 0; i != childNodes.getLength(); ++i) {
                    Node child = childNodes.item(i);
                    if (!(child instanceof Element))
                        continue;
    
                    if (child.getNodeName().equals("runAs"))
                        child.getFirstChild().setNodeValue("false");
    
                }
    
    
                session.write(flowFile1, new StreamCallback() {
                    @Override
                    public void process(InputStream inputStream1, OutputStream outputStream) throws IOException {
                        TransformerFactory transformerFactory = TransformerFactory.newInstance();
    
                        try {
                            transformer = transformerFactory.newTransformer();
                        } catch (TransformerConfigurationException e) {
                            e.printStackTrace();
                        }
                       DOMSource source1 = new DOMSource(xmlDocument);
    
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        StreamResult result = new StreamResult(bos);
    
    
                        try {
                            transformer.transform(source1, result);
                        } catch (TransformerException e) {
                            e.printStackTrace();
                        }
                        byte[] array = bos.toByteArray();
                        outputStream.write(array);
                    }
    
                });
    
    
            session.transfer(flowFile1,REL_SUCCESS);
    
    
    
            } finally {
                lock.release();
                s.close();
                ini.close();
            }
    
            try {
                FileInputStream input = new FileInputStream(file);
    
    
            } catch (FileNotFoundException e) {
                Thread.sleep(5000);
    
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    

0 个答案:

没有答案