我正在使用 JAXB 将 XML(父 XML、FIXML)转换为字符串。在那个 XML 中,一个子节点有另一个 XML(Child XML,FpML)数据,我确实有它的模式(xsd)。在父 XML 的模式中,具有子 XML 的元素类型被定义为字符串。我需要子 XML 应该作为字符串出现。请让我知道我必须做什么改变。我对 JAXB 比较陌生。提前致谢..!!
干杯, 萨克提斯
最佳答案
更新
根据您的意见:
Hi.. Thanks for your reply.. @Blaise Doughan & @CoolBeans in the above example you provide you have mentioned String Value but in my xml, instead of "String Value" there will be another XML inside it. like Richard and I need the "Richard" as string in the output. Please let me know still you want more information. Thanks.. Cheers, Sakthi. S
您可以结合使用 @XmlAnyElement 和 DomHandler 实现来处理此用例。有关详细示例,请参阅:
更新 #2
根据您的意见
Can you please tell me what is change need to be done in the schema to make that filed "@XmlAnyElement", since I am generating the java classes on the build time.
您可以使用 JAXB dom
模式注释来导致在属性上生成 XmlAnyElement:
新江西来电
xjc -d out -b bindings.xml dom.xsd
dom.xsd
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.example.com/default"
targetNamespace="http://www.example.com/default">
<xs:element name="customer">
<xs:complexType>
<xs:sequence>
<xs:element ref="address"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="address">
<xs:complexType>
<xs:attribute name="street" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:schema>
bindings.xml
<jxb:bindings
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
version="2.1">
<jxb:bindings schemaLocation="string.xsd">
<jxb:bindings node="//xs:element[@name='customer']/xs:complexType/xs:sequence/xs:element[@ref='address']">
<jxb:dom/>
</jxb:bindings>
</jxb:bindings>
</jxb:bindings>
客户
Customer
上的地址属性将使用 @XmlAnyElement
注释:
package com.example._default;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.w3c.dom.Element;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"address"
})
@XmlRootElement(name = "customer")
public class Customer {
@XmlAnyElement
protected Element address;
public Element getAddress() {
return address;
}
public void setAddress(Element value) {
this.address = value;
}
}
原始答案
您可能正在寻找@XmlValue 注释。例如,如果您有以下类(class):
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD
public class Child {
@XmlValue
private String value;
}
上面的类将编码为:
<child>String Value</child>
在相应的 XML 模式中,子元素的类型将是 xs:string。
<xs:element name="child" type="xs:string"/>
关于java - 使用 JAXB 获取子节点中的 XML 数据作为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5930406/