从文件夹中读取并更新XML标记值

时间:2016-06-08 07:35:12

标签: java xpath

我有一个文件夹(“容器”),我有一些实际上包含XML的.txt文件。所有文件都有一个公共元素<Number>,我想为所有XML文件增加1。 任何帮助。

我已经对单个.txt文件进行了更改,这没关系: -

package ParsingXML;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class ReadAndModifyXMLFile {
    public static final String xmlFilePath = "C:\\Users\\PSINGH17\\Desktop\\testFile.txt";

    public static void main(String argv[]) {

    try {

            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

            Document document = documentBuilder.parse(xmlFilePath);

            // Get employee by tag name
            //use item(0) to get the first node with tag name "employee"
            Node employee = document.getElementsByTagName("employee").item(0);

            // update employee , increment the number
            NamedNodeMap attribute = employee.getAttributes();
            Node nodeAttr = attribute.getNamedItem("number");
String str= nodeAttr.getNodeValue();
System.out.println(str);
int val= Integer.parseInt(str);
System.out.println(val);
val=val+1;
System.out.println(val);
String final_value= String.valueOf(val);
System.out.println(final_value);
            nodeAttr.setTextContent(final_value);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();

            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(document);

            StreamResult streamResult = new StreamResult(new File(xmlFilePath));
            transformer.transform(domSource, streamResult);



        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (SAXException sae) {
            sae.printStackTrace();
        }
    }
}

xml文件: -

<?xml version="1.0" encoding="UTF-8" standalone="no"?><company>


<employee number="14">

    <firstname>Pranav</firstname>

    <lastname>Singh</lastname>
    <email>pranav@example.org</email>


    <salary>1000</salary>

</employee>


</company>

1 个答案:

答案 0 :(得分:0)

因此,此代码使用哈希后的初始值数字来启动计数器。 然后它遍历文件夹中的所有文件。 第一个文件将获得初始值,其余文件将获得递增值。

    import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;

public class TestFile {
    public static final String xmlFileFolder = "C:\\Rahul\\test";
    private static final String initialValue = "450-000-1212";

    public static void main(String argv[]) {
        int baseValue = Integer.parseInt(getValueAfterLastDash(initialValue));
        System.out.println("startValue " + baseValue);
        File folder = new File(xmlFileFolder);
        for (File file : folder.listFiles()) {
            try {
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

                Document document = documentBuilder.parse(file);

                Node employee = document.getElementsByTagName("employee").item(0);
                NamedNodeMap attribute = employee.getAttributes();
                Node nodeAttr = attribute.getNamedItem("number");
                System.out.println(getValueBeforeLastDash(initialValue) + baseValue);
                nodeAttr.setTextContent(getValueBeforeLastDash(initialValue) + baseValue);

                TransformerFactory transformerFactory = TransformerFactory.newInstance();

                Transformer transformer = transformerFactory.newTransformer();
                DOMSource domSource = new DOMSource(document);

                StreamResult streamResult = new StreamResult(file);
                transformer.transform(domSource, streamResult);
                baseValue++;
            } catch (Exception ignored) {
            }
        }
    }

    private static String getValueAfterLastDash(String initialValue) {
        return initialValue.substring(initialValue.lastIndexOf('-') + 1, initialValue.length());
    }

    private static String getValueBeforeLastDash(String initialValue) {
        return initialValue.substring(0, initialValue.lastIndexOf('-') + 1);
    }
}