从XMLnode读取值

时间:2018-08-29 17:16:54

标签: java xml-parsing

我对XML解析非常陌生。我正在尝试从计算机上的共享驱动器读取XML文件,并将它们移动到另一个共享驱动器。我有下面的XML文件。我正在尝试从此XML文档中读取Test.pdf值

<?xml version="1.0" encoding="utf-8" ?> 
 <xml>
 <IndexData FileName="Test.pdf">
  <AttachmentID>3221929</AttachmentID> 
  <URI>test234555..pdf</URI> 
  <postmarkDate>2018-07-02T12:52:00.9</postmarkDate> 
  <pin>305270036</pin> 
  <scanDate>2018-07-02T12:52:00.9</scanDate> 
  <UserLogin>admin</UserLogin> 
  </IndexData>
 <IndexData FileName="Test2.pdf">
  <AttachmentID>3221931</AttachmentID> 
  <URI>Appp2.pdf</URI> 
  <postmarkDate>2018-07-02T14:19:22.5</postmarkDate> 
  <pin>305270036</pin> 
  <scanDate>2018-07-02T14:19:22.5</scanDate> 
  <UserLogin>admin</UserLogin> 
  </IndexData>
</xml>

我尝试导入import org.w3c.dom.Node;为了这。下面是我的代码:

String processXml(Node doc) {

    String fileName = null;
    try {
      DfLogger.debug(this, "Loading: " + doc.getNodeName(), null, null);

      Map<String, String> indexData = getXmlData(doc);
      fileName = indexData.get("IndexData FileName");
      if (new File(fileName).exists()) {
        import(fileName, indexData);
      }
    } catch (Exception ex) {
      DfLogger.error(this, "Error processing document.", null, ex);
      return null;
    }

    return fileName;
  }

当我尝试通过以下方式读取值时,我的FileName值始终为NULL:

 fileName = indexData.get("IndexData FileName");

下面是我的getXmlData方法。

  protected Map<String, String> getXmlData(Node xmlDataNode) {

        Map<String, String> xmlData = new HashMap<>();

        NodeList nodeList = xmlDataNode.getChildNodes();

        for (int i = 0; i < nodeList.getLength(); i++) {
          Node node = nodeList.item(i);
          if (node.getNodeType() == Node.ELEMENT_NODE) {
            xmlData.put(node.getNodeName(), node.getTextContent().trim());
          }
        }

        return xmlData;
      }

processXML的调用者方法如下:

Public void processIncomingfiles(String documentTagName) throws Exception {

    DfLogger.debug(this, "Import Process Begin ---- exportPath=" + exportPath, null, null);

    try {
      File dir = new File(exportPath);

      if (dir.isDirectory()) {
        FilenameFilter xmlFiles = new FilenameFilter() {
          public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".xml");
          }
        };

        for (File file : dir.listFiles(xmlFiles)) {
          if (!file.isDirectory()) {
            DfLogger.debug(this, "Loading XML file: " + file.getAbsolutePath(), null, null);

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

            FileInputStream fileStream = new FileInputStream(file);

            try {
              // Use FileInputStream instead of File since parse will leave file locked on error
              Document doc = documentBuilder.parse(fileStream);

              fileStream.close();
              fileStream = null;


              doc.getDocumentElement().normalize();

              NodeList nodeList = doc.getElementsByTagName(documentTagName);
              List<Node> errors = new ArrayList<>();

              for (int i = 0; i < nodeList.getLength(); i++) {
                String documentFilename = processXml(nodeList.item(i));
                if (documentFilename != null) {
                  moveFileToProcessedSuccessful(documentFilename);
                } else {
                  DfLogger.debug(
                      this,
                      "Error processing document in file: " + file.getName(),
                      null,
                      null);
                  errors.add(nodeList.item(i));
                }
              }

              if (!errors.isEmpty()) {
                if (errors.size() == nodeList.getLength()) {
                  safeMove(file, file.getAbsolutePath() + ".errors");
                } else {
                  Node parent = nodeList.item(0).getParentNode();
                  for (Node errorDoc : errors) {
                    parent.removeChild(errorDoc);
                  }

                  writeXml(doc, file.getAbsolutePath());
                  moveFileToProcessedSuccessful(file);

                  while (nodeList.getLength() > 0) {
                    parent.removeChild(nodeList.item(0));
                  }

                  for (Node errorDoc : errors) {
                    parent.appendChild(errorDoc);
                  }

                  writeXml(doc, file.getAbsolutePath() + ".errors");
                }
              } else {
                moveFileToProcessedSuccessful(file);
              }
            } catch (Exception ex) {
              DfLogger.error(this, "Error parsing XML File.", null, ex);

              if (fileStream != null) {
                fileStream.close();         // If DocBuilder.parse fails, leaves file locked
              }

              safeMove(file, file.getAbsolutePath() + ".error");
            }
          }
        }
      }
    } catch (Exception ex) {
      DfLogger.error(this, "Error in XML Parser.", null, ex);
      throw ex;
    }

    DfLogger.debug(this, "Import Process Ends -----------", null, null);
  }

  /**
   * Process the Xml for the give document node.
   * @param doc xml node
   * @return filename of successfully processed document, otherwise null
   */

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

假设您在test.xml文件中拥有xml数据。您可以使用以下代码从xml中读取文件并获取特定数据:

package yourPackage;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);

        Document doc = factory.newDocumentBuilder().parse(Files.newInputStream(Paths.get("test.xml")));
        doc.getDocumentElement().normalize();

        Element data = (Element)doc.getElementsByTagName("IndexData").item(0);
        System.out.println(data.getAttribute("FileName"));
    }
}

输出为:

Test.pdf