使用放心创建动态 xml 有效载荷

create dynamic xml payload using rest assured

发送前需要在我的请求正文中使用放心设置xml节点

<?xml version="1.0" encoding="UTF-8"?>
<shopping>
   <category type="groceries">
      <item>
         <name></name>
         <price>10</price>
      </item>
      <item>
         <name>Coffee</name>
         <price>20</price>
      </item>
   </category>
   <category type="supplies">
      <item>
         <name>Paper</name>
         <price>5</price>
      </item>
      <item quantity="4">
         <name>Pens</name>
         <price>15</price>
      </item>
   </category>
   <category type="present">
      <item when="Aug 10">
         <name>Kathryn's Birthday</name>
         <price>200</price>
      </item>
   </category>
</shopping>

我需要在发送请求之前设置"name"

  <item>
     <name></name>
     <price>10</price>
  </item>

谁能帮我设置一下吗?

您可以使用 XmlSlurper 库或 jackson(fasterxml) 库来完成此操作

您可以使用 Java 类 为您完成这项工作,而无需添加新的依赖项。

这是我的方法

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

//In my case - I have namespaces
factory.setNamespaceAware(true);

DocumentBuilder builder = factory.newDocumentBuilder();
Document myXml = builder.parse(new InputSource(new FileInputStream(PATH_TO_MY_XML)));

//Again - I have namespaces so I using this declaration
NodeList node = myXml.getDocumentElement().getElementsByTagNameNS("http://www.testsite.com/common", "site");
node.item(0).setTextContent("MY_SITE_NAME");

StringWriter writer = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer();

transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

//Transform and save to a string
transformer.transform(new DOMSource(myXml), new StreamResult(writer));
String resultXml = writer.toString();

然后只需将 resultXml 字符串作为参数发送给您的 Rest-Assured body(resultXml) 方法。 如果您使用的是 RequestSpecBuilder,则将其放在 setBody(resultXml) 方法