下面是一個示例,您需要使用@XmlAnyElement來獲取內容,因爲它沒有使用CDATA
。
Employee.java:
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Employee {
private long id;
private String name;
private int age;
public long getId() {
return id;
}
@XmlAttribute
public void setId(long id) {
this.id = id;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public String getName() {
return name;
}
@XmlAnyElement(NameHandler.class)
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
}
NameHandler.java:
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.annotation.DomHandler;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class NameHandler implements DomHandler<String, StreamResult> {
private static final String NAME_START_TAG = "<name>";
private static final String NAME_END_TAG = "</name>";
private StringWriter xmlWriter = new StringWriter();
@Override
public StreamResult createUnmarshaller(ValidationEventHandler errorHandler) {
return new StreamResult(xmlWriter);
}
@Override
public String getElement(StreamResult rt) {
String xml = rt.getWriter().toString();
int beginIndex = xml.indexOf(NAME_START_TAG) + NAME_START_TAG.length();
int endIndex = xml.indexOf(NAME_END_TAG);
return xml.substring(beginIndex, endIndex);
}
@Override
public Source marshal(String n, ValidationEventHandler errorHandler) {
try {
String xml = NAME_START_TAG + n.trim() + NAME_END_TAG;
StringReader xmlReader = new StringReader(xml);
return new StreamSource(xmlReader);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
JAXB:
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class JAXBExample {
public static void main(String[] args) {
try {
String temp ="<employee id=\"1001\"><age>25</age><name>myemp<p>content inside tags</p></name></employee>";
JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
StringReader reader = new StringReader(temp);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Employee emp = (Employee) jaxbUnmarshaller.unmarshal(reader);
System.out.println(emp);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
打印該conten t原樣:
Employee [id=1001, name=myemp<p>content inside tags</p>, age=25]
希望它有幫助。
你有沒有試過在'CDATA'中包裝元素的內容? – user3487063 2014-09-12 15:35:52
我不能這樣做,因爲我需要保持原樣的數據。 – 2014-09-12 15:44:31
「有時它們也是錯誤的」 - 但是您的XML有效嗎?如果不是,您可能需要先使用諸如JTidy之類的東西。 – lexicore 2014-09-12 18:05:01