Java 在序列化期间更改某些对象字段名
我正在使用javax.xml.bind.annotation.XmlRootElement注释对象将其序列化为xml字符串Java 在序列化期间更改某些对象字段名,java,xml,jaxb,Java,Xml,Jaxb,我正在使用javax.xml.bind.annotation.XmlRootElement注释对象将其序列化为xml字符串 JAXBContext jc = JAXBContext.newInstance(obj.getClass()); // Marshal the object to a StringWriter Marshaller marshaller = jc.createMarshaller(); marshaller.
JAXBContext jc = JAXBContext.newInstance(obj.getClass());
// Marshal the object to a StringWriter
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.example.com/schema.xsd");
StringWriter stringWriter = new StringWriter();
marshaller.marshal(obj, stringWriter);
result = stringWriter.toString();
如何更改XML中的某些节点名称,就像我在对象中有“price”,但在生成的XML文档中有“thePrice”。使用
@XmlRootElement
、@XmlElement
和@XmlAttribute
的name属性在XML文档中定义不同的名称
try {
String filepath = "c:\\file.xml";
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
// Get the root element
Node company = doc.getFirstChild();
// getElementsByTagName() to get it directly.
// Get the staff element by tag name directly
Node price = doc.getElementsByTagName("price").item(0);
// update price attribute
NamedNodeMap attr = price.getAttributes();
Node nodeAttr = attr.getNamedItem("id");
nodeAttr.setTextContent("some other price");
例如:
public class MyClass {
@XmlElement(name="thePrice")
private double price;
}
使用
@XmlRootElement
、@XmlElement
和@xmldattribute
的name属性在XML文档中定义不同的名称
例如:
public class MyClass {
@XmlElement(name="thePrice")
private double price;
}
你不能更改名称,你可以复制元素的名称,如果有类似的
<price id="12" style="color:blue"> 12.16$</price>
其中parent是price的父节点u无法更改名称,您可以复制元素like的atrybutes,如果有任何like
<price id="12" style="color:blue"> 12.16$</price>
其中parent是price的父节点这如何更改节点名称?这如何更改节点名称?