Java&Xml 튜토리얼(7) JDOM을 사용하여 XML 파일의 내용 수정

黄舟
풀어 주다: 2017-02-22 14:51:35
원래의
1862명이 탐색했습니다.

JDOM은 XML 파일을 작동하는 매우 유연한 방법을 제공합니다. JDOM 사용은 매우 간단하며 코드는 간결하고 읽기 쉽습니다. 앞서 우리는 JDOM을 사용하여 XML 파일을 구문 분석하는 방법을 배웠습니다. 이 섹션에서는 JDOM을 사용하여 XML 파일의 내용을 수정하는 방법을 소개합니다.

이 튜토리얼에서는 다음 XML 파일을 수정합니다:
employees.xml

<?xml version="1.0" encoding="UTF-8"?><Employees xmlns="http://www.journaldev.com/employees">
  <Employee id="1">
    <age>25</age>
    <name>Pankaj</name>
    <gender>Male</gender>
    <role>Java Developer</role>
  </Employee>
  <Employee id="2">
    <age>34</age>
    <name>Mona</name>
    <gender>Female</gender>
    <role>Manager</role>
  </Employee>
  <Employee id="3">
    <age>45</age>
    <name>Dave</name>
    <gender>Male</gender>
    <role>Support</role>
  </Employee></Employees>
로그인 후 복사
로그인 후 복사

xml의 각 Employee 요소를 변경합니다.
1 . 모든 이름 요소를 내용이 모두 대문자가 되도록 수정합니다.
2. 성별이 남성인 경우 id 속성 값 뒤에 M을 추가하고, 성별이 여성인 경우 id 속성 값 뒤에 F를 추가합니다.
3. 성별 요소를 삭제하세요.
4. 각 Employee 요소에 급여(salary) 하위 요소를 추가합니다. 기본값은 1000입니다.
다음은 프로그램 코드입니다.
JDOMXMLEditor.java

package com.journaldev.xml.jdom;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class JDOMXMLEditor {

    public static void main(String[] args) throws JDOMException, IOException {        
    final Namespace ns = Namespace.getNamespace("http://www.journaldev.com/employees");        
    //Get the JDOM document
        org.jdom2.Document doc = useSAXParser("employees.xml");        
        //Get list of Employee element
        Element rootElement = doc.getRootElement();
        List<Element> listEmpElement = rootElement.getChildren("Employee", ns);        
        //loop through to edit every Employee element
        for (Element empElement : listEmpElement) {            
        //change the name to BLOCK letters
            String name = empElement.getChildText("name", ns);            
            if (name != null)
                empElement.getChild("name", ns).setText(name.toUpperCase());            
                //edit the ID attribute based on Gender
            String gender = empElement.getChildText("gender", ns);            
            if (gender != null && gender.equalsIgnoreCase("female")) {
                String id = empElement.getAttributeValue("id");
                empElement.getAttribute("id").setValue(id + "F");
            } else {
                String id = empElement.getAttributeValue("id");
                empElement.getAttribute("id").setValue(id + "M");
            }            
            //remove gender element as it&#39;s not needed anymore
            empElement.removeChild("gender", ns);            
            //add salary element with default value to every employee
            empElement.addContent(new Element("salary", ns).setText("1000"));
        }        
        //document is processed and edited successfully, lets save it in new file
        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());        
        //output xml to console for debugging
        //xmlOutputter.output(doc, System.out);
        xmlOutputter.output(doc, new FileOutputStream("employees_new.xml"));
    }    //Get JDOM document from SAX Parser
    private static org.jdom2.Document useSAXParser(String fileName) throws JDOMException,
            IOException {
        SAXBuilder saxBuilder = new SAXBuilder();        
        return saxBuilder.build(new File(fileName));
    }

}
로그인 후 복사

위 코드는 네임스페이스를 사용하여 모든 요소를 ​​가져오고 프로그램을 실행하면 XML 파일 내용이 출력된다는 점에 유의해야 합니다. 🎜>employees_new.xml

<?xml version="1.0" encoding="UTF-8"?><Employees xmlns="http://www.journaldev.com/employees">
  <Employee id="1M">
    <age>25</age>
    <name>PANKAJ</name>
    <role>Java Developer</role>
    <salary>1000</salary>
  </Employee>
  <Employee id="2F">
    <age>34</age>
    <name>MONA</name>
    <role>Manager</role>
    <salary>1000</salary>
  </Employee>
  <Employee id="3M">
    <age>45</age>
    <name>DAVE</name>
    <role>Support</role>
    <salary>1000</salary>
  </Employee></Employees>
로그인 후 복사
로그인 후 복사

JDOM은 XML 파일을 작동하는 매우 유연한 방법을 제공합니다. JDOM을 사용하는 것은 매우 간단하며 코드가 간결하고 읽기 쉽습니다. 앞서 우리는 JDOM을 사용하여 XML 파일을 구문 분석하는 방법을 배웠습니다. 이 섹션에서는 JDOM을 사용하여 XML 파일의 내용을 수정하는 방법을 소개합니다.

이 튜토리얼에서는 다음 XML 파일을 수정합니다:
employees.xml

<?xml version="1.0" encoding="UTF-8"?><Employees xmlns="http://www.journaldev.com/employees">
  <Employee id="1">
    <age>25</age>
    <name>Pankaj</name>
    <gender>Male</gender>
    <role>Java Developer</role>
  </Employee>
  <Employee id="2">
    <age>34</age>
    <name>Mona</name>
    <gender>Female</gender>
    <role>Manager</role>
  </Employee>
  <Employee id="3">
    <age>45</age>
    <name>Dave</name>
    <gender>Male</gender>
    <role>Support</role>
  </Employee></Employees>
로그인 후 복사
로그인 후 복사

xml의 각 Employee 요소를 변경합니다.

1. 내용을 모두 대문자로 만듭니다.
2. 성별이 남성인 경우 id 속성 값 뒤에 M을 추가하고, 성별이 여성인 경우 id 속성 값 뒤에 F를 추가합니다.
3. 성별 요소를 삭제하세요.
4. 각 Employee 요소에 급여(salary) 하위 요소를 추가합니다. 기본값은 1000입니다.
다음은 프로그램 코드입니다.
JDOMXMLEditor.java

package com.journaldev.xml.jdom;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class JDOMXMLEditor {

    public static void main(String[] args) throws JDOMException, IOException {        
    final Namespace ns = Namespace.getNamespace("http://www.journaldev.com/employees");        
    //Get the JDOM document
        org.jdom2.Document doc = useSAXParser("employees.xml");        
        //Get list of Employee element
        Element rootElement = doc.getRootElement();
        List<Element> listEmpElement = rootElement.getChildren("Employee", ns);        
        //loop through to edit every Employee element
        for (Element empElement : listEmpElement) {            
        //change the name to BLOCK letters
            String name = empElement.getChildText("name", ns);            
            if (name != null)
                empElement.getChild("name", ns).setText(name.toUpperCase());            
                //edit the ID attribute based on Gender
            String gender = empElement.getChildText("gender", ns);            
            if (gender != null && gender.equalsIgnoreCase("female")) {
                String id = empElement.getAttributeValue("id");
                empElement.getAttribute("id").setValue(id + "F");
            } else {
                String id = empElement.getAttributeValue("id");
                empElement.getAttribute("id").setValue(id + "M");
            }            
            //remove gender element as it&#39;s not needed anymore
            empElement.removeChild("gender", ns);            
            //add salary element with default value to every employee
            empElement.addContent(new Element("salary", ns).setText("1000"));
        }        //document is processed and edited successfully, lets save it in new file
        XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());        
        //output xml to console for debugging
        //xmlOutputter.output(doc, System.out);
        xmlOutputter.output(doc, new FileOutputStream("employees_new.xml"));
    }    //Get JDOM document from SAX Parser
    private static org.jdom2.Document useSAXParser(String fileName) throws JDOMException,
            IOException {
        SAXBuilder saxBuilder = new SAXBuilder();        
        return saxBuilder.build(new File(fileName));
    }

}
로그인 후 복사

위 코드는 네임스페이스를 사용하여 모든 요소를 ​​가져오고 프로그램을 실행하면 XML 파일 내용이 출력된다는 점에 유의해야 합니다. 🎜>employees_new.xml

<?xml version="1.0" encoding="UTF-8"?><Employees xmlns="http://www.journaldev.com/employees">
  <Employee id="1M">
    <age>25</age>
    <name>PANKAJ</name>
    <role>Java Developer</role>
    <salary>1000</salary>
  </Employee>
  <Employee id="2F">
    <age>34</age>
    <name>MONA</name>
    <role>Manager</role>
    <salary>1000</salary>
  </Employee>
  <Employee id="3M">
    <age>45</age>
    <name>DAVE</name>
    <role>Support</role>
    <salary>1000</salary>
  </Employee></Employees>
로그인 후 복사
로그인 후 복사

위는 JDOM을 사용하여 XML 파일의 내용을 수정하는 Java&Xml 튜토리얼(7)입니다. 더 많은 관련 내용은 PHP 중국어 웹사이트(www.php.cn)를 참고하세요. )!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!