Java 从XMLnode读取值
我对XML解析非常陌生。我正在尝试从计算机上的共享驱动器读取XML文件,并将其移动到另一个共享驱动器。我有下面的XML文件。我正在尝试从这个XML文档中读取Test.pdf值Java 从XMLnode读取值,java,xml-parsing,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&g
<?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>
下面是我的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;
}
受保护的映射getXmlData(节点xmlDataNode){
Map xmlData=newhashmap();
NodeList NodeList=xmlDataNode.getChildNodes();
for(int i=0;i
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
*/
Public void processIncomingfiles(String documentTagName)引发异常{
debug(这个“导入过程开始----exportPath=“+exportPath,null,null”);
试一试{
文件目录=新文件(导出路径);
if(dir.isDirectory()){
FilenameFilter xmlFiles=newfilenamefilter(){
公共布尔接受(文件目录,字符串名称){
返回name.toLowerCase().endsWith(“.xml”);
}
};
for(文件:dir.listFiles(xmlFiles)){
如果(!file.isDirectory()){
debug(这是“加载XML文件:”+file.getAbsolutePath(),null,null);
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder DocumentBuilder=dbFactory.newDocumentBuilder();
FileInputStream fileStream=新的FileInputStream(文件);
试一试{
//使用FileInputStream而不是File,因为解析将使文件在出现错误时处于锁定状态
Document doc=documentBuilder.parse(fileStream);
fileStream.close();
fileStream=null;
doc.getDocumentElement().normalize();
NodeList NodeList=doc.getElementsByTagName(documentTagName);
列表错误=新建ArrayList();
for(int i=0;i0){
父.removeChild(节点列表项(0));
}
对于(节点错误文档:错误){
父.子(errorDoc);
}
writeXml(doc,file.getAbsolutePath()+“.errors”);
}
}否则{
moveFileToProcessedSuccessful(文件);
}
}捕获(例外情况除外){
error(这是“解析XML文件时出错”,null,ex);
if(fileStream!=null){
fileStream.close();//如果DocBuilder.parse失败,文件将保持锁定
}
safeMove(文件,file.getAbsolutePath()+“.error”);
}
}
}
}
}捕获(例外情况除外){
error(这是“XML解析器中的错误”,null,ex);
掷骰子;
}
debug(这个“导入过程结束------------”,null,null);
}
/**
*处理给定文档节点的Xml。
*@param doc xml节点
*@返回已成功处理文档的文件名,否则为空
*/
任何帮助都将不胜感激。假设您在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
确切地说,
getXmlData()
方法是什么?对不起,忘了放getXmlData()方法。刚刚编辑了我的postHi-Emre,我可以用我现有的getXMLdata代码阅读。我之所以这样问,是因为这段代码是由其他人编写的,我被要求保留这段代码。您的问题中有一些遗漏点,比如import()
方法的实现是什么,或者processXml()的调用者的实现是什么。因此,除了提供的答案,我帮不了你更多。您可以进行一些重构,而不是保留现有代码。导入方法只是将XML文件移动到另一个共享文件夹。基本上,我正在尝试从本地驱动器读取XML文件并将其放入共享驱动器。我把我的代码放在processIncomingfiles上,这是ProcessXml的调用者,没关系,我明白了。我从你的代码中得到了帮助。谢谢。我很高兴这对你有帮助
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