2017-04-20 128 views
0

林上的文件夹中读取XML文件,然后让其中的XML文件中顺便说一句,这是我的XML文件看起来像获取文件夹

<?xml version="1.0" encoding="UTF-8"?> -<Config> <Name>MyName</Name> ..... </Config> 
<name> MyName </name>程序工作的XML元素的值

我想要得到的<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] 
+0

假设这个[示例](https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/)是有一个解决方案,并且具有更好地解决您的问题。 –

+0

Yoow @RajithPemabandu谢谢我没有看到谷歌上的链接 – user123040569

回答

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()); 
+0

Yey它的工作原理!谢啦。 – user123040569