通过FTP在特定节点之间附加XML节点-Java

时间:2018-08-29 18:19:47

标签: java xml ftp-client

我已经搜索过,但是找不到我需要的东西。

我需要打开一个存储在FTP上的XML文件,然后我必须列出所有节点并插入一个新节点。

请看下面的XML示例。

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>data2</loc>
        <priority>1.0</priority>
    </url>

    <url>
        <loc>data1</loc>
         <priority>1.0</priority>
    </url>
</urlset>

我正在检索文件:

    String filename = "test.xml";
    String server = "...";
    int port = 21;
    String user = "...";
    String pass = "...";

    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(server, port);
    ftpClient.login(user, pass);

    ftpClient.enterLocalPassiveMode();

    /*filePath deve ser o ftp?*/
    FileOutputStream fos = new FileOutputStream(filename);
    ftpClient.retrieveFile("folder/" + filename, fos);

现在,我想在此文件内附加另一个XML节点,例如,得到以下结果:这意味着我想在XML的第一个元素之前附加-> n.insertBefore(NODE,n.getFirstChild( ));然后再次将其保存在FTP上。

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>data3 - NEW DATA</loc>
        <priority>1.0</priority>
    </url>
    <url>
        <loc>data2</loc>
        <priority>1.0</priority>
    </url>

    <url>
        <loc>data1</loc>
         <priority>1.0</priority>
    </url>
</urlset>

我知道可以下载文件,打开,附加然后上载。但就我而言,我做不到。我必须附加文件而不是覆盖它。

我可以对存储为以下内容的本地文件执行此操作。

public class XMLWriter {

     /*
     * @param args the command line arguments
     */

    public static void main(String[] args) throws Exception 
    {
        MethodWrite2();
    }


    public static void MethodWrite2() throws org.xml.sax.SAXException, TransformerException, IOException, ParserConfigurationException
    {          
        String filePath = "teste.xml";
        File xmlFile = new File(filePath);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;

        dBuilder = dbFactory.newDocumentBuilder();
        Document doc;
        doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();

        Node n = doc.getElementsByTagName("urlset").item(0);
        ContadorDeNosXml(doc); // count Node numbers and print the content of an attribute of each node
        /*cria uma lista de especiais a serem adicionados no XML*/
        List<NovoEspecial> listaDeNovosEspeciais = new ArrayList<NovoEspecial>();


        /*loop para adicionar um novo especial a lista de novos especiais que serão adicionados no XML*/
        /*necessário correção -> OBS nr: (1)*/
        for (int i = 0 ; i <= 10; i++)
        {
            /*pra cada 1, cria uma instancia e adiciona a lista de novos especiais a serem adicionados no XML*/
             NovoEspecial novoEspecial = new NovoEspecial("data", Integer.toString(i));
             listaDeNovosEspeciais.add(novoEspecial);
        }

        /*pra cada item da lista de novos especiais a serem adicionados no XML*/
        for(NovoEspecial novoEspecial : listaDeNovosEspeciais)
        {   
            Element urlTag = CreateXmlNode(doc, novoEspecial);          
            // INSERE NO INICIO/ANTES DO PRIMEIRO ELEMENTO, DESSA FORMA FICANDO DO MAIS NOVO PARA O MAIS ANTIGO
            n.insertBefore(urlTag, n.getFirstChild());   
        }

        doc.getDocumentElement().normalize();

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();

        //SETA IDENTAÇÃO NO PADRAO DO XML.APACHE COM 4 ESPAÇOS
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        DOMSource domSource = new DOMSource(doc);
        StreamResult streamResult = new StreamResult(filePath);            
        transformer.transform(domSource, streamResult);

    } //MethodWrite2


    public static Element CreateXmlNode(Document doc, NovoEspecial novoEspecial)
    {
        // CRIA A TAG URL
        Element urlTag = doc.createElement("url");
        // CRIA A TAG LOC E ESCREVE DENTRO DELA O LINK DO NOVO ESPECIAL
        Element loc = doc.createElement("loc");
        loc.appendChild(doc.createTextNode(novoEspecial.getUrl()));

        //CRIA A TAG PRIORITY E ESCREVE DENTRO DELA O VALOR ATRIBUIDO
        Element priority = doc.createElement("priority");
        priority.appendChild(doc.createTextNode( novoEspecial.getPriority()));

        // ADICIONA AS TAGS PRIORITY E LOC DENTRO DA TAG URL
        urlTag.appendChild(loc);
        urlTag.appendChild(priority);

        return urlTag;
    }

    public static void ContadorDeNosXml(Document doc)
    {
        NodeList nodeLst = doc.getElementsByTagName("url");
        List<NovoEspecial> listaDeNovosEspeciais = new ArrayList<NovoEspecial>();
        System.out.println(nodeLst.getLength());

        for(int i =0; i < nodeLst.getLength(); i++)
        {
            Node locNode = doc.getElementsByTagName("loc").item(i);
            Node priorityNode = doc.getElementsByTagName("priority").item(i);

            NovoEspecial novoEspecial = new NovoEspecial(locNode.getTextContent(), priorityNode.getTextContent());

            System.out.println("ContadorDeNosXml URL = " + novoEspecial.getUrl() );
            System.out.println("ContadorDeNosXml Priority = " + novoEspecial.getPriority());
        }
    }
}

public class NovoEspecial
{
    private String url;
    private String priority;

    //constructor
    protected NovoEspecial(String url, String priority)
    {
        setUrl(url);
        setPriority(priority);
    }

    //getters
    public String getUrl()
    {
        return url;
    }
    public String getPriority()
    {
        return priority;
    }

    //setters
    private void setUrl(String url)
    {
        this.url = url;
    }
    private void setPriority(String priority)
    {
        this.priority = priority;
    }
}

感谢您的帮助。

搜索:

How can I write to a remote file using Apache Commons Net?

How do I append a node to an existing XML file in java

How to read and write xml files?

How to append text to an existing file in Java

0 个答案:

没有答案