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;
다음은 판독기입니다(String 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로 더 많은 마법(저장, 로드, 전송, 조작)을 수행할 수 있는 편안한 방법이 필요합니다.
여기가 X스트림이 빛나는 곳입니다.데이터를 보관하는 클래스에 주석을 달거나 해당 클래스를 변경하지 않으려면 마샬링(개체 -> xml) 또는 마샬링 해제(xml -> 개체)를 위해 Xstream 인스턴스를 구성합니다.
내부적으로 XStream은 reflection, readObject 및 readResolve 메서드를 표준 Java 객체 직렬화에 사용합니다.
여기에서 빠르고 효과적인 튜토리얼을 보실 수 있습니다.
어떻게 작동하는지 간략하게 설명하기 위해 마샬과 언마셜이 데이터 구조로 구성된 샘플 코드도 제공합니다.링합니다.main
나머지는 테스트 개체를 생성하고 데이터를 채우기 위한 코드일 뿐입니다.구성은 매우 간단합니다.xStream
인스턴스(instance)와 마샬링(marshalling)/마스링 해제(unmarshalling)는 각각 코드 한 줄로 이루어집니다.
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 데이터에 읽기 및 쓰기 가능한 보기를 제공하는 라이브러리를 자바 인터페이스로 사용하여 XML 구조와 자바 구조를 분리할 수 있습니다.자습서에서:
주어진 실제 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
파서는 a와 다르게 작업하고 있습니다.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 file 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();
}
}
}
결과
시작 요소 : 회사
시작 요소 : 직원
시작 요소 : 이름
이름 : 용
끝 요소 : 이름
시작 요소 : 성
성 : mook kim
끝 요소 : 성
시작 요소 : 닉네임
닉네임 : mkyong
끝 요소 : 닉네임
등등...
출처(마이콩) - 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' 카테고리의 다른 글
텍스트 영역을 WordPress TinyMCE wp_editor()로 바꾸기 (0) | 2023.09.24 |
---|---|
mariadb JSON_UNCOTEGET's overned's special characters (0) | 2023.09.24 |
MySQL "Alter Table Add Column After Column"의 성능 - 큰 테이블에서 (0) | 2023.09.19 |
IntelliJ와 로컬 MySQL을 연결하는 방법은? (0) | 2023.09.19 |
MySQL 쿼리에서 세미콜론을 생략하는 것이 나쁜가요? (0) | 2023.09.19 |