我想知道如何从XML文件中获取数据到我的java代码中。为此我将创建我的XML文件,然后将编写一个Java代码。然后我将尝试从XML获取数据到java。为此,一些映射必须在我的java代码中完成,或者我必须使用一些java API。请帮助你学习或给我一些学习的链接!
答案 0 :(得分:3)
答案 1 :(得分:0)
您也可以使用Spring的Jaxb2Marshaller
。首先,您需要在Spring上下文中创建Jaxb2Marshaller
bean,指定要为marshaller绑定的类以及定义XML的模式:
<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.example.Employee</value>
<value>com.example.Department</value>
</list>
</property>
<property name="schemas">
<list>
<value>classpath:schemas/schema.xsd</value>
</list>
</property>
</bean>
在您的代码中,获取字符串XML并使用marshaller来解组对象。例如:
@Autowire
private Jaxb2Marshaller marshaller;
...
final Employee employee = (Employee) marshaller.unmarshal(new StreamSource(new StringReader(xmlString)));
答案 2 :(得分:0)
您可以使用DOM XML Parser(JAXP)。以下示例取自mkyong
<company>
<staff id="1001">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff id="2001">
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>
java代码:
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("/Users/mkyong/staff.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Staff id : " + eElement.getAttribute("id"));
System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}