我想知道如何从 XML 文件中获取数据到我的 java 代码中。为此,我将创建我的 XML 文件,然后编写 java 代码。然后我将尝试从 XML 获取数据到 java。为此,必须在我的 java 代码中完成一些映射,或者我必须使用一些 java API。请帮助您的知识或提供一些学习链接!
问问题
34256 次
3 回答
2
您可以使用 DOM XML 解析器 (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();
}
}
}
于 2013-06-30T12:40:03.667 回答
0
您也可以Jaxb2Marshaller
从 Spring 中使用。首先,您需要Jaxb2Marshaller
在 Spring 上下文中创建 bean,指定要为编组器绑定的类以及定义 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 并使用编组器来解组对象。例如:
@Autowire
private Jaxb2Marshaller marshaller;
...
final Employee employee = (Employee) marshaller.unmarshal(new StreamSource(new StringReader(xmlString)));
于 2013-06-30T12:28:44.643 回答