1 回答

TA貢獻1777條經驗 獲得超3個贊
您需要編寫擴展類的自定義適配器。在您的情況下,我們可以創建一個表示所有屬性的。讀取屬性后,您可以使用反射或手動設置所有字段。動態讀取所有屬性的自定義刪除程序可能如下所示:javax.xml.bind.annotation.adapters.XmlAdapterMapPOJO
class ItemXmlAdapter extends XmlAdapter<Object, Item> {
@Override
public Item unmarshal(Object v) {
Element element = (Element) v;
Map<String, String> properties = new HashMap<>();
NamedNodeMap attributes = element.getAttributes();
for (int i = attributes.getLength() - 1; i >= 0; i--) {
Node node = attributes.item(i);
properties.put(node.getNodeName(), node.getNodeValue());
}
Item item = new Item();
item.setProperties(properties);
return item;
}
@Override
public Object marshal(Item v) throws Exception {
return null; // Implement if needed
}
}
讀取和解析所有屬性的簡單示例應用程序:XML
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JaxbApp {
public static void main(String[] args) throws Exception {
File xmlFile = new File("./resource/test.xml").getAbsoluteFile();
JAXBContext context = JAXBContext.newInstance(Root.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Root root = (Root) unmarshaller.unmarshal(xmlFile);
System.out.println(root);
}
}
@XmlRootElement(name = "root")
class Root {
private List<Item> items = new ArrayList<>();
@XmlElement(name = "object")
public List<Item> getItems() {
return items;
}
// getters, setters, toString
}
@XmlJavaTypeAdapter(ItemXmlAdapter.class)
class Item {
private Map<String, String> properties;
// getters, setters, toString
}
對于以下內容:XML
<root>
<object att1="orgA" att2="orgA" id="6" name="N"/>
<object att5="some" id="6" name="value"/>
</root>
指紋:
Items{items=[{name=N, id=6, att2=orgA, att1=orgA}, {name=value, att5=some, id=6}]}
添加回答
舉報