XMLEncoder를 사용하여 빠른 직렬화 루틴을 작성하고 다음 XML을 얻었습니다.
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.7.0_25" class="java.beans.XMLDecoder">
<object class="edu.stevens.Test">
<void property="id">
<int>1</int>
</void>
<void property="name">
<string>Fred</string>
</void>
</object>
</java>
더 간결한 것은 말할 것도없고 더 의미있는 태그를 정의하고 싶습니다. 이 같은:
<Test>
<id>1</id>
<name>Fred</name>
</Test>
한 번 파일에 패키지 이름을 포함하는 것을 신경 쓰지 않을 것이지만, 크기가 커질 수 있기 때문에 매번 복제되는 것은 원하지 않습니다.
분명히 직렬화를 통해 작업을 수행 한 다음 나중에 XSLT 변환 단계를 실행할 수 있지만 속도가 느리고 번거 롭습니다.
객체에 대한 태그 매핑을 정의 할 수있는 방법이 있다면 이것이 제 최고의 선택입니다. 그렇지 않은 경우 작동하는 다른 XML 직렬화 도구가 있습니까?
일반적으로 다음과 같은 객체를 포함하는 객체가 필요합니다.
<Quiz>
<id>1</id>
<name>foo</name>
<Question>
<id>1</id>
<text>What kind of question is this?</text>
<audio>foo.mp3</audio>
<MultipleChoice>
<Answer correct="t">rhetorical</Answer>
<Answer>stupid</Answer>
<Answer>funny</Answer>
</MultipleChoice>
<text>another part to this question, what is 2+2?</text>
<Fillin>
<id>2</id>
</Fillin>
</Question>
</Quiz>
속성으로 직렬화하는 것을 선호합니다.
하지만 더 어렵다면 큰 문제가 아닙니다.
여기 XML로 /에서 사용자 정의 직렬화 / 역 직렬화 샘플이 있습니다.
여기에서 코드 실행 : http://ideone.com/H3oHBn
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class CustomSaveLoad {
static class Container {
Container Container1;
Container Container2;
AnotherContainer AnotherContainer;
String name;
}
static class AnotherContainer {
String name;
int value;
}
static Document save(Object obj) throws Exception {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
save(obj, obj.getClass().getSimpleName(), doc, doc);
return doc;
}
static void save(Object obj, String name, Node parent, Document doc) throws Exception {
Class<?> objCls = obj.getClass();
Element elt = doc.createElement(name);
parent.appendChild(elt);
if (objCls.getCanonicalName().startsWith(CustomSaveLoad.class.getSimpleName())) {
for (Field field : objCls.getDeclaredFields()) {
Object value = field.get(obj);
if (value != null) {
save(value, field.getName(), elt, doc);
}
}
} else {
elt.setTextContent(obj.toString());
}
}
static <E> E load(Document doc, Class<E> cls) throws Exception {
Element elt = doc.getDocumentElement();
E obj = cls.newInstance();
load(obj, elt);
return obj;
}
static void load(Object obj, Element elt) throws Exception {
Class<?> cls = obj.getClass();
NodeList children = elt.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
Element childElt = (Element) children.item(i);
Field field = cls.getDeclaredField(childElt.getTagName());
Class<?> childCls = field.getType();
if (childCls.getCanonicalName().startsWith(CustomSaveLoad.class.getSimpleName())) {
Object childObj = childCls.newInstance();
field.set(obj, childObj);
load(childObj, childElt);
} else {
String value = childElt.getTextContent();
if (childCls == String.class) {
field.set(obj, value);
} else {
childCls = toWrapper(childCls);
Method method = childCls.getMethod("valueOf", String.class);
field.set(obj, method.invoke(null, value));
}
}
}
}
}
static Class<?> toWrapper(Class<?> cls) {
if (cls.isPrimitive()) {
if (Integer.TYPE == cls) {
cls = Integer.class;
} else if (Double.TYPE == cls) {
cls = Double.class;
}
}
return cls;
}
public static void main(String[] args) throws Exception {
Container rootContainer = new Container();
rootContainer.name = "root";
rootContainer.Container1 = new Container();
rootContainer.Container1.name = "root.c1";
rootContainer.Container2 = new Container();
rootContainer.Container2.name = "root.c2";
rootContainer.AnotherContainer = new AnotherContainer();
rootContainer.AnotherContainer.name = "root.c3";
rootContainer.AnotherContainer.value = 42;
rootContainer.Container2.AnotherContainer = new AnotherContainer();
rootContainer.Container2.AnotherContainer.name = "root.c2.c3";
rootContainer.Container2.AnotherContainer.value = 21;
Document doc = save(rootContainer);
StreamResult result = new StreamResult(new StringWriter());
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", 2);
Transformer transform = transformerFactory.newTransformer();
transform.setOutputProperty(OutputKeys.INDENT, "yes");
transform.transform(new DOMSource(doc), result);
String xml = result.getWriter().toString();
System.out.println("Saved to xml:");
System.out.println(xml);
Container loadedContainer = load(doc, Container.class);
System.out.println(loadedContainer.Container2.AnotherContainer.value);
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다