>  기사  >  Java  >  Java 개발에서 XML 및 속성 구성 파일을 읽는 방법

Java 개발에서 XML 및 속성 구성 파일을 읽는 방법

高洛峰
高洛峰원래의
2017-01-12 10:27:031608검색

관련 자료:

Ajax를 사용하여 파일 및 기타 매개변수 업로드(java 개발)

1. XML 파일:

XML이란? XML은 일반적으로 전자 문서를 구조화하기 위해 표시하는 데 사용되는 마크업 언어인 Standard Universal Markup Language의 하위 집합인 Extensible Markup Language를 나타냅니다.

2. XML 파일의 장점:

1) XML 문서의 내용과 구조가 완전히 분리되어 있습니다.
2) 강력한 상호 운용성.
3) 표준화와 통일.
4) 다양한 인코딩을 지원합니다.
5) 강력한 확장성.

3. XML 문서를 구문 분석하는 방법:

XML은 다른 언어의 XML 문서를 동일하게 구문 분석하지만 구현되는 구문은 두 가지 기본 구문 분석 방법이 다릅니다. 첫 번째는 XML 파일의 순서에 따라 단계별로 XML 파일을 구문 분석하는 SAX 메서드입니다. 또 다른 파싱 방법은 DOM 방식인데, DOM 파싱의 핵심은 노드이다. DOM4J, JDOM 및 기타 방법도 있습니다. 본 글에서는 DOM, DOM4J 방식과 이를 툴 클래스로 캡슐화하여 XML 문서를 읽는 방식을 소개한다.

4.XML 문서:

scores.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE students [
 <!ELEMENT students (student+)>
 <!ELEMENT student (name,course,score)>
 <!ATTLIST student id CDATA #REQUIRED>
 <!ELEMENT name (#PCDATA)>
 <!ELEMENT course (#PCDATA)>
 <!ELEMENT score (#PCDATA)>
]>
<students>
 <student id="11">
  <name>张三</name>
  <course>JavaSE</course>
  <score>100</score>
 </student>
 <student id="22"> 
  <name>李四</name>
  <course>Oracle</course>
  <score>98</score>
 </student>
</students>

5.DOM 구문 분석 XML

public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
  //1.创建DOM解析器工厂
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  //2.由DOM解析器工厂创建DOM解析器
  DocumentBuilder db = dbf.newDocumentBuilder();
  //3.由DOM解析器解析文档,生成DOM树
  Document doc = db.parse("scores.xml");
  //4.解析DOM树,获取文档内容(元素 属性 文本)
  //4.1获取根元素scores
  NodeList scoresList = doc.getChildNodes();
  Node scoresNode = scoresList.item(1);
  System.out.println(scoresList.getLength());
  //4.2获取scores中所有的子元素student
  NodeList studentList = scoresNode.getChildNodes();
  System.out.println(studentList.getLength());
  //4.3对每个student进行处理
  for(int i=0;i<studentList.getLength();i++){
   Node stuNode = studentList.item(i);
   //System.out.println(stuNode.getNodeType());
   //输出元素的属性 id
   if(stuNode.getNodeType()==Node.ELEMENT_NODE){
    Element elem =(Element)stuNode;
    String id= elem.getAttribute("id");
    System.out.println("id------>"+id);
   }
   //输出元素的子元素 name course score
   NodeList ncsList = stuNode.getChildNodes();
   //System.out.println(ncsList.getLength() );
   for(int j=0;j<ncsList.getLength();j++){
    Node ncs = ncsList.item(j);
    if(ncs.getNodeType() == Node.ELEMENT_NODE){
      String name = ncs.getNodeName();
      //String value = ncs.getFirstChild().getNodeValue();//文本是元素的子节点,所以要getFirstChild
      String value = ncs.getTextContent();
      System.out.println(name+"----->"+value);
    }
   }
   System.out.println();
  }
 }

6.DOM4J 구문 분석 XML 문서:

public static void main(String[] args) throws DocumentException {
 //使用dom4j解析scores2.xml,生成dom树
 SAXReader reader = new SAXReader();
 Document doc = reader.read(new File("scores.xml")); 
 //得到根节点:students
 Element root = doc.getRootElement(); 
 //得到students的所有子节点:student
 Iterator<Element> it = root.elementIterator();
 //处理每个student
 while(it.hasNext()){
  //得到每个学生
  Element stuElem =it.next();
  //System.out.println(stuElem);
  //输出学生的属性:id
  List<Attribute> attrList = stuElem.attributes();
  for(Attribute attr :attrList){
   String name = attr.getName();
   String value = attr.getValue();
   System.out.println(name+"----->"+value);
  }
  //输出学生的子元素:name,course,score
  Iterator <Element>it2 = stuElem.elementIterator();
  while(it2.hasNext()){
   Element elem = it2.next();
   String name = elem.getName();
   String text = elem.getText();
   System.out.println(name+"----->"+text);
  }
  System.out.println();
 }
}

물론 아니요. XML을 구문 분석하는 데 어떤 방법을 사용하든 jar 패키지를 가져와야 합니다(잊지 마세요).

7. 나만의 방식:

실제 개발 프로젝트에서는 툴 클래스를 잘 활용하고, 반복적으로 사용하는 기능을 툴 클래스에 담아야 하므로 다음과 같은 방법이 있습니다.

7.1 속성 파일이란:

7.1.1 구조적으로:

.xml 파일은 주로 나무 모양의 문서입니다.
.properties 파일은 주로 키-값 쌍의 형태로 존재합니다

7.1.2 유연한 관점에서:

.xml 파일은 .properties 파일보다 더 유연합니다.

7.1.3 편의성 측면에서:

.properties 파일 구성은 .xml 파일 구성보다 간단합니다.

7.1.4 애플리케이션 관점에서:

.properties 파일은 .xml이 더 유연하기 때문에 작고 단순한 프로젝트에 더 적합합니다.

7.2 내 속성 문서:

내 프로젝트에 path.properties 파일을 만들었습니다. 이 파일은 내가 사용하려는 경로를 저장하는 데 사용되며 name = 형식으로 저장됩니다. 값. 예:

realPath = D:/file/

7.3 자신의 .properties 파일을 구문 분석합니다.

public class PropertiesUtil {
 private static PropertiesUtil manager = null;
 private static Object managerLock = new Object();
 private Object propertiesLock = new Object();
 private static String DATABASE_CONFIG_FILE = "/path.properties";
 private Properties properties = null;
 public static PropertiesUtil getInstance() {
  if (manager == null) {
   synchronized (managerLock) {
    if (manager == null) {
     manager = new PropertiesUtil();
    }
   }
  }
  return manager;
 }
 private PropertiesUtil() {
 }
 public static String getProperty(String name) {
  return getInstance()._getProperty(name);
 }
 private String _getProperty(String name) {
  initProperty();
  String property = properties.getProperty(name);
  if (property == null) {
   return "";
  } else {
   return property.trim();
  }
 }
 public static Enumeration<?> propertyNames() {
  return getInstance()._propertyNames();
 }
 private Enumeration<?> _propertyNames() {
  initProperty();
  return properties.propertyNames();
 }
 private void initProperty() {
  if (properties == null) {
   synchronized (propertiesLock) {
    if (properties == null) {
     loadProperties();
    }
   }
  }
 }
 private void loadProperties() {
  properties = new Properties();
  InputStream in = null;
  try {
   in = getClass().getResourceAsStream(DATABASE_CONFIG_FILE);
   properties.load(in);
  } catch (Exception e) {
   System.err
     .println("Error reading conf properties in PropertiesUtil.loadProps() "
       + e);
   e.printStackTrace();
  } finally {
   try {
    in.close();
   } catch (Exception e) {
   }
  }
 }
 /**
  * 提供配置文件路径
  *
  * @param filePath
  * @return
  */
 public Properties loadProperties(String filePath) {
  Properties properties = new Properties();
  InputStream in = null;
  try {
   in = getClass().getResourceAsStream(filePath);
   properties.load(in);
  } catch (Exception e) {
   System.err
     .println("Error reading conf properties in PropertiesUtil.loadProperties() "
       + e);
   e.printStackTrace();
  } finally {
   try {
    in.close();
   } catch (Exception e) {
   }
  }
  return properties;
 }
}

이를 사용하기 전에 .properties 파일의 이름인 DATABASE_CONFIG_FILE 속성에 값을 연결하기만 하면 클래스 이름을 직접 사용하여 값을 얻을 수 있습니다. .properties 파일의 키는 realPath의 내용입니다.

위는 편집자가 소개한 Java 개발에서 XML 및 속성 구성 파일을 읽는 방법입니다. 궁금한 사항이 있으면 메시지를 남겨주시면 편집자가 도와드리겠습니다. 즉시 모두에게 답장을 보내주세요!

Java 개발 시 XML 및 속성 구성 파일을 읽는 방법과 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.