如何以编程方式更新 XML 正文并打印更新的正文



下面是我的输入XML正文,它存储在src/test/resources中:

<Customer>
<Id>1</Id>
<Name>John</Name>
<Age>23</Age>
</Customer>

我想将此XML主体传递到下面的java方法中,重新设置名称,然后将其发布到HTTP URL:

public void updateXMLBodyAndPost(String newName(){
File file = new File("src\testresources\customerDetails.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer1 = (Customer) jaxbUnmarshaller.unmarshal(file);
customer1.setName(newName);
System.out.println("Customer details: " + customer1.toString());
}

上面,我可以设置新名称。 然后,我正在尝试打印出更新的XML正文

但是,打印出来的是:

客户详细信息:Customer@7ba4f24f

我需要对代码进行哪些更改,以便在控制台中打印出以下内容:

<Customer>
<Id>1</Id>
<Name>updatedName</Name>
<Age>23<Age>
</Customer>
Customer details: Customer@7ba4f24f

您得到这个是因为您正在调用.toString()并且您没有包含它的实现。

默认情况下,每个对象(在Customer的情况下(都有一个默认toString()这将导致与您类似的响应。您可以在此处阅读有关默认toString()的信息。

重写字符串:

public class Customer {
private String name;
private String id;
private String age;
@Override
public String toString() {
return "Customer{" +
"name='" + name + ''' +
", id='" + id + ''' +
", age='" + age + ''' +
'}';
}
}

您可以修改默认toString()并使其返回 xml,但我认为这不是一个好主意,因为toString()不是为此而设计的。

我宁愿创建一个单独的方法,您可以在其中从文件中解组 xml,并使用修改的客户数据将其封送回来。

您可以按以下方式进行封送处理:

File file = Paths.get("src/main/resources/customer.xml").toFile();
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer1 = (Customer) jaxbUnmarshaller.unmarshal(file);
customer1.setName(newName);
// overriding toString
System.out.println("Customer details with toString: " + customer1.toString());
// print it nicely using JAXB
final Marshaller marshaller = jaxbContext.createMarshaller();
StringWriter sw = new StringWriter();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer1, sw);
String xmlString = sw.toString();
System.out.println("Customer details with JAXB.marshal: n" + xmlString);

这将打印:

Customer details with toString: Customer{name='dsadadada', id='1', age='23'}
Customer details with JAXB.marshal: 
<Customer>
<Name>dsadadada</Name>
<Id>1</Id>
<Age>23</Age>
</Customer>

相关内容

最新更新