获取文件文件夹中的XML元素的值

时间:2017-04-20 00:36:48

标签: java xml

我正在处理一个读取文件夹中的xml文件的程序,然后获取xml文件中的<name> MyName </name>,这是我的xml文件看起来像

 <?xml version="1.0" encoding="UTF-8"?> -<Config> <Name>MyName</Name> ..... </Config>

我想获得<name>的价值,这就是我现在所拥有的

File directory = new File(txtSource.getText());
            File[] fList = directory.listFiles();
            for (File file : fList) {
                if (file.getName().startsWith("Config")) {
                    try {
                        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder builder = factory.newDocumentBuilder();
                        Document document = builder.parse(new File(file.toString()));
                        Element rootElement = document.getDocumentElement();
                        rootElement.getAttribute("name");
                        System.out.println(rootElement);
                    } catch (ParserConfigurationException | SAXException | IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

我尝试了我的代码,这是错误的输出

[Config: null]

1 个答案:

答案 0 :(得分:0)

试试这个。

    File directory = new File(txtSource.getText());
    File[] fList = directory.listFiles();
    for (File file : fList) {
        if (file.getName().startsWith("Config")) {
            try {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document document = builder.parse(file);
                Element rootElement = document.getDocumentElement();
                NodeList nameTags = rootElement.getElementsByTagName("Name");
                Node nameTag = nameTags.item(0);
                System.out.println("tag name: " + nameTag.getNodeName());
                System.out.println("tag text: " + nameTag.getFirstChild().getNodeValue());