XML 파일을 읽고 쓰는 방법은 무엇입니까?
XML 파일 을 읽고 써야 합니다. Java를 사용하여 XML 파일을 읽고 쓰는 가장 쉬운 방법은 무엇입니까?
다음은 dtd로 간단한 xml 파일을 읽고 쓰는 방법을 보여주는 간단한 DOM 예제입니다.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE roles SYSTEM "roles.dtd">
<roles>
<role1>User</role1>
<role2>Author</role2>
<role3>Admin</role3>
<role4/>
</roles>
및 dtd :
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT roles (role1,role2,role3,role4)>
<!ELEMENT role1 (#PCDATA)>
<!ELEMENT role2 (#PCDATA)>
<!ELEMENT role3 (#PCDATA)>
<!ELEMENT role4 (#PCDATA)>
먼저 다음을 가져옵니다.
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.xml.sax.*;
import org.w3c.dom.*;
다음은 필요한 몇 가지 변수입니다.
private String role1 = null;
private String role2 = null;
private String role3 = null;
private String role4 = null;
private ArrayList<String> rolev;
다음은 독자입니다 (문자열 xml은 xml 파일의 이름입니다).
public boolean readXML(String xml) {
rolev = new ArrayList<String>();
Document dom;
// Make an instance of the DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use the factory to take an instance of the document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// parse using the builder to get the DOM mapping of the
// XML file
dom = db.parse(xml);
Element doc = dom.getDocumentElement();
role1 = getTextValue(role1, doc, "role1");
if (role1 != null) {
if (!role1.isEmpty())
rolev.add(role1);
}
role2 = getTextValue(role2, doc, "role2");
if (role2 != null) {
if (!role2.isEmpty())
rolev.add(role2);
}
role3 = getTextValue(role3, doc, "role3");
if (role3 != null) {
if (!role3.isEmpty())
rolev.add(role3);
}
role4 = getTextValue(role4, doc, "role4");
if ( role4 != null) {
if (!role4.isEmpty())
rolev.add(role4);
}
return true;
} catch (ParserConfigurationException pce) {
System.out.println(pce.getMessage());
} catch (SAXException se) {
System.out.println(se.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
return false;
}
그리고 여기 작가 :
public void saveToXML(String xml) {
Document dom;
Element e = null;
// instance of a DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// use factory to get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
// create instance of DOM
dom = db.newDocument();
// create the root element
Element rootEle = dom.createElement("roles");
// create data elements and place them under root
e = dom.createElement("role1");
e.appendChild(dom.createTextNode(role1));
rootEle.appendChild(e);
e = dom.createElement("role2");
e.appendChild(dom.createTextNode(role2));
rootEle.appendChild(e);
e = dom.createElement("role3");
e.appendChild(dom.createTextNode(role3));
rootEle.appendChild(e);
e = dom.createElement("role4");
e.appendChild(dom.createTextNode(role4));
rootEle.appendChild(e);
dom.appendChild(rootEle);
try {
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd");
tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
// send DOM to file
tr.transform(new DOMSource(dom),
new StreamResult(new FileOutputStream(xml)));
} catch (TransformerException te) {
System.out.println(te.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
} catch (ParserConfigurationException pce) {
System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
}
}
getTextValue는 다음과 같습니다.
private String getTextValue(String def, Element doc, String tag) {
String value = def;
NodeList nl;
nl = doc.getElementsByTagName(tag);
if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
value = nl.item(0).getFirstChild().getNodeValue();
}
return value;
}
몇 가지 접근 자와 뮤 테이터를 추가하면 완료됩니다!
JAXB (Java Architecture for XML Binding)를 사용하여 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();
}
}
}
위의 답변은 DOM 파서 (일반적으로 전체 파일을 메모리에서 읽고 파싱합니다. 큰 파일의 경우 문제가 됨) 만 다룹니다. 메모리를 덜 사용하고 더 빠른 SAX 파서를 사용할 수 있습니다 (어쨌든 암호).
SAX 파서는 요소의 시작, 요소의 끝, 속성, 요소 사이의 텍스트 등을 찾을 때 일부 함수를 콜백하므로 문서를 구문 분석하고 동시에 필요한 것을 얻을 수 있습니다.
몇 가지 예제 코드 :
http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
답변은 DOM / SAX 및 JAXB 예제의 복사 붙여 넣기 구현 만 다룹니다.
그러나 XML을 사용할 때의 한 가지 큰 영역이 없습니다. 많은 프로젝트 / 프로그램에서 일부 기본 데이터 구조를 저장 / 검색 할 필요가 있습니다. 귀하의 프로그램에는 멋지고 반짝이는 비즈니스 객체 / 데이터 구조에 대한 클래스가 이미 있습니다.이 데이터를 XML 구조로 변환하는 편리한 방법을 원하여 더 많은 마법을 수행 할 수 있습니다 (XSLT로 저장,로드, 전송, 조작). .
이것이 XStream이 빛나는 곳입니다. 데이터를 보관하는 클래스에 주석을 달거나 해당 클래스를 변경하지 않으려면 마샬링 (objects-> xml) 또는 unmarshalling (xml-> objects)을위한 XStream 인스턴스를 구성합니다.
내부적으로 XStream은 리플렉션, 표준 Java 객체 직렬화의 readObject 및 readResolve 메소드를 사용합니다.
여기 에서 훌륭하고 빠른 튜토리얼을 얻을 수 있습니다 .
작동 방식에 대한 간략한 개요를 제공하기 위해 데이터 구조를 마샬링 및 언 마샬링하는 샘플 코드도 제공합니다. 마샬링 / 마샬링 해제는 main
메서드 에서 모두 발생 하고 나머지는 테스트 개체를 생성하고 데이터를 채우는 코드 일뿐입니다. xStream
인스턴스 를 구성하는 것은 매우 간단 하며 마샬링 / 언 마샬링은 각각 한 줄의 코드로 수행됩니다.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
public class XStreamIsGreat {
public static void main(String[] args) {
XStream xStream = new XStream();
xStream.alias("good", Good.class);
xStream.alias("pRoDuCeR", Producer.class);
xStream.alias("customer", Customer.class);
Producer a = new Producer("Apple");
Producer s = new Producer("Samsung");
Customer c = new Customer("Someone").add(new Good("S4", 10, new BigDecimal(600), s))
.add(new Good("S4 mini", 5, new BigDecimal(450), s)).add(new Good("I5S", 3, new BigDecimal(875), a));
String xml = xStream.toXML(c); // objects -> xml
System.out.println("Marshalled:\n" + xml);
Customer unmarshalledCustomer = (Customer)xStream.fromXML(xml); // xml -> objects
}
static class Good {
Producer producer;
String name;
int quantity;
BigDecimal price;
Good(String name, int quantity, BigDecimal price, Producer p) {
this.producer = p;
this.name = name;
this.quantity = quantity;
this.price = price;
}
}
static class Producer {
String name;
public Producer(String name) {
this.name = name;
}
}
static class Customer {
String name;
public Customer(String name) {
this.name = name;
}
List<Good> stock = new ArrayList<Good>();
Customer add(Good g) {
stock.add(g);
return this;
}
}
}
좋아, 이미 답변 목록에 DOM, JaxB 및 XStream이 있지만 XML을 읽고 쓰는 완전히 다른 방법이 있습니다 . 데이터 프로젝션 읽기 및 쓰기 가능한보기를 제공하는 라이브러리를 사용하여 XML 구조와 Java 구조를 분리 할 수 있습니다. XML 데이터에 Java 인터페이스로. 로부터 자습서 :
실제 XML을 감안할 때 :
<weatherdata>
<weather
...
degreetype="F"
lat="50.5520210266113" lon="6.24060010910034"
searchlocation="Monschau, Stadt Aachen, NW, Germany"
... >
<current ... skytext="Clear" temperature="46"/>
</weather>
</weatherdata>
데이터 프로젝션을 사용하여 프로젝션 인터페이스를 정의 할 수 있습니다.
public interface WeatherData {
@XBRead("/weatherdata/weather/@searchlocation")
String getLocation();
@XBRead("/weatherdata/weather/current/@temperature")
int getTemperature();
@XBRead("/weatherdata/weather/@degreetype")
String getDegreeType();
@XBRead("/weatherdata/weather/current/@skytext")
String getSkytext();
/**
* This would be our "sub projection". A structure grouping two attribute
* values in one object.
*/
interface Coordinates {
@XBRead("@lon")
double getLongitude();
@XBRead("@lat")
double getLatitude();
}
@XBRead("/weatherdata/weather")
Coordinates getCoordinates();
}
그리고 POJO와 마찬가지로이 인터페이스의 인스턴스를 사용합니다.
private void printWeatherData(String location) throws IOException {
final String BaseURL = "http://weather.service.msn.com/find.aspx?outputview=search&weasearchstr=";
// We let the projector fetch the data for us
WeatherData weatherData = new XBProjector().io().url(BaseURL + location).read(WeatherData.class);
// Print some values
System.out.println("The weather in " + weatherData.getLocation() + ":");
System.out.println(weatherData.getSkytext());
System.out.println("Temperature: " + weatherData.getTemperature() + "°"
+ weatherData.getDegreeType());
// Access our sub projection
Coordinates coordinates = weatherData.getCoordinates();
System.out.println("The place is located at " + coordinates.getLatitude() + ","
+ coordinates.getLongitude());
}
이것은 XML을 생성하는 경우에도 작동하며 XPath 표현식은 쓰기가 가능합니다.
SAX
파서는 파서와 다르게 작동하며 문서를 메모리에 DOM
로드하거나 XML
문서의 객체 표현을 생성하지 않습니다 XML
. 대신 SAX
파서는 콜백 함수 org.xml.sax.helpers.DefaultHandler
를 사용 하여 클라이언트에게 XML
문서 구조 를 알립니다 .
SAX
파서는 파서보다 빠르며 메모리를 적게 사용합니다 DOM
. 다음 SAX
콜백 메소드를 참조하십시오 .
startDocument()
및 endDocument()
– XML 문서의 시작과 끝에서 호출되는 메소드. startElement()
및 endElement()
– 문서 요소의 시작과 끝에서 호출되는 메소드. characters()
– XML 문서 요소의 시작 태그와 끝 태그 사이에 텍스트 내용을 사용하여 호출되는 메소드.
- XML 파일
간단한 XML 파일을 만듭니다.
<?xml version="1.0"?>
<company>
<staff>
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff>
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>
- XML 파서 :
Java 파일 SAX 구문 분석기를 사용하여 XML 파일을 구문 분석합니다.
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean bfname = false;
boolean blname = false;
boolean bnname = false;
boolean bsalary = false;
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
System.out.println("Start Element :" + qName);
if (qName.equalsIgnoreCase("FIRSTNAME")) {
bfname = true;
}
if (qName.equalsIgnoreCase("LASTNAME")) {
blname = true;
}
if (qName.equalsIgnoreCase("NICKNAME")) {
bnname = true;
}
if (qName.equalsIgnoreCase("SALARY")) {
bsalary = true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
System.out.println("End Element :" + qName);
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bfname) {
System.out.println("First Name : " + new String(ch, start, length));
bfname = false;
}
if (blname) {
System.out.println("Last Name : " + new String(ch, start, length));
blname = false;
}
if (bnname) {
System.out.println("Nick Name : " + new String(ch, start, length));
bnname = false;
}
if (bsalary) {
System.out.println("Salary : " + new String(ch, start, length));
bsalary = false;
}
}
};
saxParser.parse("c:\\file.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
결과
Start Element :company
Start Element :staff
Start Element :firstname
First Name : yong
End Element :firstname
Start Element :lastname
Last Name : mook kim
End Element :lastname
Start Element :nickname
Nick Name : mkyong
End Element :nickname
and so on...
Source(MyKong) - http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
참고URL : https://stackoverflow.com/questions/7373567/how-to-read-and-write-xml-files
'programing tip' 카테고리의 다른 글
반복기와 열거 자의 구별 (0) | 2020.11.01 |
---|---|
문자열의 일부를 제거하지만 문자열의 끝에있을 때만 (0) | 2020.11.01 |
.NET 짧은 고유 식별자 (0) | 2020.11.01 |
부모 div에서 불투명도를 설정하고 자식 div에 영향을 미치지 않는 방법은 무엇입니까? (0) | 2020.11.01 |
Java에서 임의의 문자열을 생성하는 방법 (0) | 2020.10.31 |