如何在使用JAXb解析后将XML文件打印到控制台。XML有一个根级别,然后有一系列不同的表结构。
公共类ExternalImports {
public static void main(String[] args) {
try {
// create JAXB context and initializing Marshaller
JAXBContext jaxbContext = JAXBContext.newInstance(ServiceModel.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
// specify the location and name of xml file to be read
File XMLfile = new File(
"C:\\Users\\Data.xml");
ServiceModel model = (ServiceModel) jaxbUnmarshaller.unmarshal(XMLfile);
System.out.println(model);XML结构(示例代码)
<Service-Model>
<component_t action="str1234">
<type>12</type>
<name>str1234</name>
<attributes>str1234</attributes>
<component_heirarchy>
<supplier>str1234</supplier>
</component_heirarchy>
</sqm_component_t>
</Service-Model>我正试图找到一种方法,一或两行代码,以打印它的所有控制台。否则,写50到60行打印语句是一项乏味的工作。
这就是我在控制台上得到的全部。
com.group.project.serviceModelTools.ServiceModel@77396f71
发布于 2015-12-22 21:04:22
此方法将任何POJO java类序列化为格式化的xml字符串:
public String serialize( Object aMessageDto) throws Exception
{
JAXBContext jaxbContext = JAXBContext.newInstance( aMessageDto.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty( Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, SCHEMA_FILE);
StringWriter sw = new StringWriter();
marshaller.marshal( aMessageDto, sw);
return sw.toString();
}就这么说吧:
System.out.println( serialize( myObj)); https://stackoverflow.com/questions/34424190
复制相似问题