我想阅读并从我的文件xml中获取信息

时间:2015-03-07 10:33:36

标签: xml listview

我的xml是:

<?xml version="1.0" encoding="UTF-8"?><Applications xmlns="http://www.journaldev.com/application">

<application>

<nom>ma premiere application</nom>

<messagerie>0</messagerie>

<repertoire>0</repertoire>

<calculatrice>1</calculatrice>

<calendrier>1</calendrier>

</application>

<application>

<nom>ma dexieme application</nom>

<messagerie>1</messagerie>

<repertoire>0</repertoire>

<calculatrice>1</calculatrice>

<calendrier>1</calendrier>
</application>

<application>
<nom>ma troisieme application</nom>

<messagerie>1</messagerie>

<repertoire>1</repertoire>

<calculatrice>1</calculatrice>

<calendrier>1</calendrier>

</application>

</Applications>

1 个答案:

答案 0 :(得分:0)

public class ModifyXMLDOM {

    public static void main(String[] args) {
        String filePath = "employee.xml";
        File xmlFile = new File(filePath);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(xmlFile);
            doc.getDocumentElement().normalize();

            //update attribute value
            updateAttributeValue(doc);

            //update Element value
            updateElementValue(doc);

            //delete element
            deleteElement(doc);

            //add new element
            addElement(doc);

            //write the updated document to file or console
            doc.getDocumentElement().normalize();
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File("employee_updated.xml"));
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(source, result);
            System.out.println("XML file updated successfully");

        } catch (SAXException | ParserConfigurationException | IOException | TransformerException e1) {
            e1.printStackTrace();
        }
    }

    private static void addElement(Document doc) {
        NodeList employees = doc.getElementsByTagName("Employee");
        Element emp = null;

        //loop for each employee
        for(int i=0; i<employees.getLength();i++){
            emp = (Element) employees.item(i);
            Element salaryElement = doc.createElement("salary");
            salaryElement.appendChild(doc.createTextNode("10000"));
            emp.appendChild(salaryElement);
        }
    }

    private static void deleteElement(Document doc