Java> XML>按标记名称获取内容并更改内容

时间:2013-04-24 02:38:49

标签: java xml

这是我的XML文件。

<config> <properties> 
<entry key="delivaryDate">15-FEBRUARY-2013</entry> 
<entry key="externalCOID">123456</entry> 
<entry key="inputFileName">Generic_ChipONLY.chp</entry> 
<entry key="recordTotal">2</entry> 
<entry key="dueDate">15-MARCH-2013</entry>
</properties> </config>

例如,我想将“recordTotal”中的记录从2更改为10,我该怎么做? 现在我只知道使用getElementsByTagName(“entry”)。

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("customer.xml"));
NodeList entry = doc.getElementsByTagName("entry");

1 个答案:

答案 0 :(得分:0)

 String xmlFile = "customer.xml";

            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(xmlFile);

            //Retrieve the third entry node
            Node entryNode = doc.getElementsByTagName("entry").item(3);

            //Set new value
            entryNode.setTextContent("10");

            //Save to file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(xmlFile));
            transformer.transform(source, result);