Java-读取XML文件
我试图从XML文件中读取一些数据,但遇到麻烦,我拥有的XML如下:
<xml version="1.0" encoding="UTF-8"?><EmailSettings>
<recipient>test@test.com</recipient>
<sender>test2@test.com</sender>
<subject>Sales Query</subject>
<description>email body message</description>
</EmailSettings>
我试图将这些值作为字符串读取到我的Java程序中,到目前为止,我已经编写了以下代码:
private static Document getDocument (String filename){ try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setIgnoringElementContentWhitespace(true);
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new InputSource(filename));
}
catch (Exception e){
System.out.println("Error reading configuration file:");
System.out.println(e.getMessage());
}
return null;
}
Document doc = getDocument(configFileName);
Element config = doc.getDocumentElement();
我正在努力读取实际的字符串值。
回答:
可能的实现之一:
File file = new File("userdata.xml");DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();
与XML内容一起使用时:
<credentials> <user>testusr</user>
<password>testpwd</password>
</credentials>
结果"testusr"
并"testpwd"
分配给上述usr
和pwd
参考。
以上是 Java-读取XML文件 的全部内容, 来源链接: utcz.com/qa/398628.html