0
因此,我有一個類XmlReader,它能夠從xml文件加載並返回客戶端(由我定義)的實體列表。但是,我也可能有一個xml文件,其類型爲「電影」或任何其他類型的實體,我希望我的XmlReader能夠從文件中讀取和檢索。我聽說可以按順序使用反射的東西做一個通用的XmlReader類,但我不知道該怎麼做..任何人都可以幫助我嗎?提前致謝!我對XmlReader類代碼:Java:使用反射的通用XML閱讀器
public class XmlReader<ID, T extends MyObject<ID>>
{
private String fileName;
public XmlReader(String fileName)
{
this.fileName = fileName;
}
public List<Client> loadEntities()
{
List<Client> entities = new ArrayList<>();
XmlHelper docXml = new XmlHelper();
Document document = docXml.loadDocument(this.fileName);
document.getDocumentElement().normalize();
Element root = document.getDocumentElement();
NodeList clientElements = root.getElementsByTagName("field");
int id=-1;
String name="";
for (int i=0; i < clientElements.getLength(); i++)
{
Node clientElement = clientElements.item(i);
Element el = (Element) clientElement;
if (clientElement.getNodeType() != Node.ELEMENT_NODE)
{
// ignoring element due to wrong node type
continue;
}
if (el.hasAttribute("name") && el.getAttribute("name").equals("id"))
{
id = Integer.parseInt(el.getAttribute("value"));
}
if (el.hasAttribute("name") && el.getAttribute("name").equals("name"))
{
name = el.getAttribute("value");
}
if (i % 2 ==1)
{
Client newClient = new Client(id, name);
entities.add(newClient);
}
}
return entities;
}
}
和XML文件的樣子:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Clients>
<entity class="class Domain.Client">
<field name="name" type="class java.lang.String" value="Liviu"/>
<field name="id" type="class java.lang.Object" value="1"/>
</entity>
</Clients>