Java - 读取 XML 文件

2022-09-01 08:20:29

我正在尝试从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();

不过,我正在努力读取实际的字符串值。


答案 1

其中一种可能的实现:

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"usrpwd


答案 2

以简单的方式读取 xml:

http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

} 

.

package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

          } catch (JAXBException e) {
              e.printStackTrace();
          }

    }
}

推荐