如何使用JMS Serializer将带嵌套节点的XML反序列化为单个实体?
Absolutely! You can skip creating those tedious intermediate entities like Idt, Main, or Adr1 when deserializing XML to a single entity with JMS Serializer. There are straightforward ways to map nested XML nodes directly to properties on your target entity—right in line with the approach you referenced with the XmlRawExecutive class.
Using @XmlPath (Recommended for Flexibility)
The @XmlPath annotation is purpose-built for this scenario, letting you use XPath-like expressions to target nested nodes or attributes directly. Here's a concrete example:
Sample XML Structure
<Root> <Idt> <UserId>12345</UserId> <UserCode>USR001</UserCode> </Idt> <Main> <UserName>John Doe</UserName> <Email>john@example.com</Email> </Main> <Adr1 city="New York"/> </Root>
Target Entity with Direct Mapping
use JMS\Serializer\Annotation as Serializer; class User { /** * @Serializer\XmlPath("Idt/UserId/text()") * @Serializer\Type("integer") */ private int $userId; /** * @Serializer\XmlPath("Idt/UserCode/text()") * @Serializer\Type("string") */ private string $userCode; /** * @Serializer\XmlPath("Main/UserName/text()") * @Serializer\Type("string") */ private string $userName; /** * @Serializer\XmlPath("Main/Email/text()") * @Serializer\Type("string") */ private string $email; /** * @Serializer\XmlPath("Adr1/@city") * @Serializer\Type("string") */ private string $city; // Add getters and setters as needed }
The text() suffix targets the inner text of the nested node, while @city selects the attribute value of the Adr1 node—no intermediate classes required.
Alternative: Using @SerializedName with Dot-Separated Paths
For simpler nested structures, you can also use the @SerializedName annotation with dot-separated paths to point to nested nodes:
use JMS\Serializer\Annotation as Serializer; class User { /** * @Serializer\SerializedName("Idt.UserId") * @Serializer\Type("integer") * @Serializer\XmlElement(cdata=false) */ private int $userId; /** * @Serializer\SerializedName("Main.UserName") * @Serializer\Type("string") * @Serializer\XmlElement(cdata=false) */ private string $userName; // Other properties follow the same pattern }
This works well for basic nesting, but @XmlPath is more powerful for complex scenarios (like handling XML namespaces, conditional selections, or deeper nested structures).
Key Takeaway
Both approaches eliminate the need to create extra关联实体 (association entities) like Idt or Main. You can directly map any nested XML node or attribute to a property on your single target entity, streamlining your deserialization workflow exactly as you wanted.
内容的提问来源于stack exchange,提问作者Hakim

