读取Xml数据并以动态方式存储在文本文件中

时间:2012-08-07 11:34:20

标签: java xml xml-parsing

我需要读取XMl数据并将其存储在文本文件中,在上面的代码中我很难编码所有标签名称的getTagValue,如果它们是4个标签名称我可以硬编码getTagValue但是现在我有200个标签,我怎么能无需硬编码getTagValue

即可将数据读入文本文件

1 个答案:

答案 0 :(得分:0)

当使用DOM来解析XML时,你必须知道XML的确切结构,因此没有真正的方法来避免你正在做的事情。

如果您有一个XSD(如果没有,您可以编写一个),您可以使用某些Xml绑定框架(如XmlBeans)从中生成Java对象,然后使用一行来解析XML并开始使用常规的java对象。

示例代码为:

File xmlFile = new File("c:\employees.xml"); 

// Bind the instance to the generated XMLBeans types.
EmployeesDocument empDoc = 
    EmployeesDocument.Factory.parse(xmlFile); 

// Get and print pieces of the XML instance.
Employees emps = empDoc.getEmployees(); 
Employee[] empArray = emps.getEmployeeArray(); 
for (int i = 0; i < empArray.length; i++) 
{ 
    System.out.println(empArray[i]); 
}