Java - 读取XML文件 [英] Java - Reading XML file

查看:111
本文介绍了Java - 读取XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从XML文件读取一些数据并遇到一些麻烦,我的XML如下:

I am trying to read in some data from an XML file and having some trouble, the XML I have is as follows:

<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程序,到目前为止我已编写此代码:

I am trying to read these values as strings into my Java program, I have written this code so far:

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

我现在正在努力阅读实际的字符串值。

I am struggling with reading in the actual string values though.

推荐答案

其中一个可能的实现:

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内容一起使用时:

when used with the XML content:

<credentials>
    <user>testusr</user>
    <password>testpwd</password>
</credentials>

产生testusrtestpwd被分配到上面的 usr pwd 引用。

results in "testusr" and "testpwd" getting assigned to the usr and pwd references above.

这篇关于Java - 读取XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆